diff --git a/examples/eso_model_version_example/server/plugin.ts b/examples/eso_model_version_example/server/plugin.ts index a5109acafaf9e..72c412a97fd6a 100644 --- a/examples/eso_model_version_example/server/plugin.ts +++ b/examples/eso_model_version_example/server/plugin.ts @@ -330,7 +330,7 @@ export class EsoModelVersionExample const objectsCreated = await Promise.all( documentVersionConstants.map(async (obj) => { const createdDoc: WriteResponseBase = - await elasticsearch.client.asInternalUser.create(obj); + await elasticsearch.client.asInternalUser.create(obj); const parts = createdDoc._id.split(':', 2); return { type: parts[0], id: parts[1] }; }) diff --git a/examples/search_examples/public/search/app.tsx b/examples/search_examples/public/search/app.tsx index c1ffceb561fe4..177d75244da06 100644 --- a/examples/search_examples/public/search/app.tsx +++ b/examples/search_examples/public/search/app.tsx @@ -181,13 +181,15 @@ export const SearchExamplesApp = ({ const aggs = [{ type: metricAggType, params: { field: selectedNumericField!.name } }]; const aggsDsl = data.search.aggs.createAggConfigs(dataView, aggs).toDsl(); + const body = { + aggs: aggsDsl, + query, + }; + const req = { params: { index: dataView.title, - body: { - aggs: aggsDsl, - query, - }, + ...body, }, // Add a custom request parameter to be consumed by `MyStrategy`. ...(strategy ? { get_cool: getCool } : {}), @@ -197,7 +199,7 @@ export const SearchExamplesApp = ({ setAbortController(abortController); // Submit the search request using the `data.search` service. - setRequest(req.params.body); + setRequest(body); setRawResponse({}); setWarningContents([]); setIsLoading(true); diff --git a/examples/search_examples/public/search_sessions/app.tsx b/examples/search_examples/public/search_sessions/app.tsx index aca66a3953524..0198c387c6649 100644 --- a/examples/search_examples/public/search_sessions/app.tsx +++ b/examples/search_examples/public/search_sessions/app.tsx @@ -707,10 +707,8 @@ function doSearch( const req = { params: { index: dataView.title, - body: { - aggs: aggsDsl, - query, - }, + aggs: aggsDsl, + query, }, }; diff --git a/examples/search_examples/server/routes/server_search_route.ts b/examples/search_examples/server/routes/server_search_route.ts index 3e8ecdf07eed5..b1617b5202b30 100644 --- a/examples/search_examples/server/routes/server_search_route.ts +++ b/examples/search_examples/server/routes/server_search_route.ts @@ -39,12 +39,10 @@ export function registerServerSearchRoute(router: IRouter [ diff --git a/packages/kbn-performance-testing-dataset-extractor/src/es_client.ts b/packages/kbn-performance-testing-dataset-extractor/src/es_client.ts index 97d0c390d8aee..c2ffcd44a8fed 100644 --- a/packages/kbn-performance-testing-dataset-extractor/src/es_client.ts +++ b/packages/kbn-performance-testing-dataset-extractor/src/es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SearchRequest, MsearchRequestItem } from '@elastic/elasticsearch/lib/api/types'; import { ToolingLog } from '@kbn/tooling-log'; @@ -109,6 +109,8 @@ export class ESClient { username: options.username, password: options.password, }, + Connection: HttpConnection, + requestTimeout: 30_000, }); this.log = log; } diff --git a/src/core/packages/elasticsearch/server-internal/src/elasticsearch_service.ts b/src/core/packages/elasticsearch/server-internal/src/elasticsearch_service.ts index 83eb04832121e..85b0cfe756a4b 100644 --- a/src/core/packages/elasticsearch/server-internal/src/elasticsearch_service.ts +++ b/src/core/packages/elasticsearch/server-internal/src/elasticsearch_service.ts @@ -116,7 +116,7 @@ export class ElasticsearchService this.esNodesCompatibility$ = esNodesCompatibility$; - this.clusterInfo$ = getClusterInfo$(this.client.asInternalUser); + this.clusterInfo$ = getClusterInfo$(this.client.asInternalUser).pipe(takeUntil(this.stop$)); registerAnalyticsContextProvider(deps.analytics, this.clusterInfo$); return { diff --git a/src/core/packages/elasticsearch/server-internal/src/is_scripting_enabled.test.ts b/src/core/packages/elasticsearch/server-internal/src/is_scripting_enabled.test.ts index e94981d88966b..4289ed415e122 100644 --- a/src/core/packages/elasticsearch/server-internal/src/is_scripting_enabled.test.ts +++ b/src/core/packages/elasticsearch/server-internal/src/is_scripting_enabled.test.ts @@ -8,7 +8,7 @@ */ import { isRetryableEsClientErrorMock } from './is_scripting_enabled.test.mocks'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { isInlineScriptingEnabled } from './is_scripting_enabled'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_delete.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_delete.test.ts index 8f3ac9539a72f..3fb046bf3014b 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_delete.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_delete.test.ts @@ -18,7 +18,7 @@ import { } from '../repository.test.mock'; import type { Payload } from '@hapi/boom'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsBulkDeleteObject, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.isolated.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.isolated.test.ts index 9c24ab6d68d4e..fcbbb019e1b26 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.isolated.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.isolated.test.ts @@ -11,7 +11,7 @@ import { getSavedObjectFromSourceMock, rawDocExistsInNamespaceMock, } from './bulk_get.isolated.test.mocks'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObject, CheckAuthorizationResult } from '@kbn/core-saved-objects-server'; import { apiContextMock, ApiExecutionContextMock } from '../../mocks'; import { performBulkGet } from './bulk_get'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.test.ts index 0485a094e6298..0b3d86923201a 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_get.test.ts @@ -17,7 +17,7 @@ import { import type { ISavedObjectsSecurityExtension } from '@kbn/core-saved-objects-server'; import type { Payload } from '@hapi/boom'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsBulkGetObject } from '@kbn/core-saved-objects-api-server'; import { type SavedObjectsRawDocSource, type SavedObject } from '@kbn/core-saved-objects-server'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_update.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_update.test.ts index aad268ee3f7f9..57a4fa545d9e2 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_update.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/bulk_update.test.ts @@ -17,7 +17,7 @@ import { } from '../repository.test.mock'; import type { Payload } from '@hapi/boom'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsBulkUpdateObject, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/check_conflicts.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/check_conflicts.test.ts index e67c6b623aa6a..e1806a07124d2 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/check_conflicts.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/check_conflicts.test.ts @@ -13,7 +13,7 @@ import { mockGetSearchDsl, } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ALL_NAMESPACES_STRING } from '@kbn/core-saved-objects-utils-server'; import { SavedObjectsRepository } from '../repository'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/create.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/create.test.ts index 6473af396945e..3b1ba7ed37bcf 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/create.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/create.test.ts @@ -16,7 +16,7 @@ import { mockGetSearchDsl, } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsCreateOptions } from '@kbn/core-saved-objects-api-server'; import { diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/delete.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/delete.test.ts index 349b1b767c9cf..c8bf3694e4709 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/delete.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/delete.test.ts @@ -16,7 +16,7 @@ import { mockGetSearchDsl, } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsDeleteOptions } from '@kbn/core-saved-objects-api-server'; import { ALL_NAMESPACES_STRING } from '@kbn/core-saved-objects-utils-server'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.isolated.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.isolated.test.ts index a3d5778083574..986d2e8dae30f 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.isolated.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.isolated.test.ts @@ -8,7 +8,7 @@ */ import { isSupportedEsServerMock } from './find.isolated.test.mocks'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObject, AuthorizationTypeMap } from '@kbn/core-saved-objects-server'; import { apiContextMock, ApiExecutionContextMock } from '../../mocks'; import { performFind } from './find'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.ts index ee3f98eade3d5..3dace33471355 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/find.ts @@ -8,7 +8,7 @@ */ import Boom from '@hapi/boom'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { isSupportedEsServer } from '@kbn/core-elasticsearch-server-internal'; import { SavedObjectsErrorHelpers, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/get.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/get.test.ts index 01828dedcb031..c6a543f091b1c 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/get.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/get.test.ts @@ -15,7 +15,7 @@ import { mockGetSearchDsl, } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsBaseOptions } from '@kbn/core-saved-objects-api-server'; import { ALL_NAMESPACES_STRING } from '@kbn/core-saved-objects-utils-server'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/increment_counter.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/increment_counter.test.ts index 88ce6fb865f57..5ce1681933c6a 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/increment_counter.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/increment_counter.test.ts @@ -16,7 +16,7 @@ import { mockGetSearchDsl, } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsIncrementCounterField, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.test.ts index e16ef3aacacf0..2b2ddd5d41592 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.test.ts @@ -65,7 +65,6 @@ describe('preflightCheckForCreate', () => { docs: results.map(({ found, disabled }, i) => { return found ? { - // @ts-expect-error _id: params!.docs![i]._id, // needed for mockRawDocExistsInNamespaces mock implementation and existingDocument assertions _index: 'doesnt-matter', _source: { diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.ts index 4bae59efefdca..98968236c855c 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/preflight_check_for_create.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; import { type ISavedObjectTypeRegistry, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/update_objects_spaces.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/update_objects_spaces.ts index 747db5976f004..a548c5bd62fe6 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/update_objects_spaces.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/internals/update_objects_spaces.ts @@ -8,7 +8,7 @@ */ import pMap from 'p-map'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import intersection from 'lodash/intersection'; import type { Logger } from '@kbn/logging'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/remove_references_to.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/remove_references_to.test.ts index 9ea3b3aaf8229..6ec56b30d06b5 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/remove_references_to.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/remove_references_to.test.ts @@ -15,7 +15,7 @@ import { mockGetSearchDsl, } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObjectsRepository } from '../repository'; import { loggerMock } from '@kbn/logging-mocks'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/update.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/update.test.ts index 7881947f58cc1..026c576400279 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/update.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/update.test.ts @@ -11,7 +11,7 @@ import { mockGetCurrentTime, mockPreflightCheckForCreate } from '../repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { type SavedObjectUnsanitizedDoc, type SavedObjectReference, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/es_responses.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/es_responses.ts index 0079d276bbe29..2eb7c252f3f63 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/es_responses.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/es_responses.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; /** * Type and type guard function for converting a possibly not existent doc to an existent doc. diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/internal_utils.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/internal_utils.ts index 411d452b1a82f..7380f2a5b0400 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/internal_utils.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/apis/utils/internal_utils.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { Payload } from '@hapi/boom'; import { SavedObjectsErrorHelpers, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/point_in_time_finder.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/point_in_time_finder.ts index 7342690a4024a..ab769ca7a7e5e 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/point_in_time_finder.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/point_in_time_finder.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { Logger } from '@kbn/logging'; import type { SavedObjectsFindOptions, diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/repository.encryption_extension.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/repository.encryption_extension.test.ts index 5c1a9ecfce2a6..6a7d912b3b0c4 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/repository.encryption_extension.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/repository.encryption_extension.test.ts @@ -14,7 +14,7 @@ import { mockGetSearchDsl, } from './repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObjectsRepository } from './repository'; import { loggerMock } from '@kbn/logging-mocks'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/repository.security_extension.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/repository.security_extension.test.ts index cd527c497356a..b3a9b7aa99dc8 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/repository.security_extension.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/repository.security_extension.test.ts @@ -17,7 +17,7 @@ import { import { SavedObjectsRepository } from './repository'; import { loggerMock } from '@kbn/logging-mocks'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { SavedObjectsBulkUpdateObject } from '@kbn/core-saved-objects-api-server'; import { SavedObjectsSerializer } from '@kbn/core-saved-objects-base-server-internal'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/repository.spaces_extension.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/repository.spaces_extension.test.ts index c880baadb5eed..4b443fafa7bab 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/repository.spaces_extension.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/repository.spaces_extension.test.ts @@ -18,7 +18,7 @@ import { mockDeleteLegacyUrlAliases, } from './repository.test.mock'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObjectsRepository } from './repository'; import { loggerMock } from '@kbn/logging-mocks'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.test.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.test.ts index 79cfd0c582458..b6b5de1479aa1 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.test.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { validateAndConvertAggregations } from './validation'; type AggsMap = Record; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.ts index 3ee6d7077499a..85eb9ca6edf34 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/search/aggregations/validation.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ObjectType } from '@kbn/config-schema'; import { isPlainObject, isArray } from 'lodash'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/lib/search/search_dsl/search_dsl.ts b/src/core/packages/saved-objects/api-server-internal/src/lib/search/search_dsl/search_dsl.ts index 90bb8ae96fb8f..b806e38586c73 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/lib/search/search_dsl/search_dsl.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/lib/search/search_dsl/search_dsl.ts @@ -9,7 +9,7 @@ import Boom from '@hapi/boom'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsPitParams } from '@kbn/core-saved-objects-api-server'; import type { ISavedObjectTypeRegistry } from '@kbn/core-saved-objects-server'; import type { IndexMapping } from '@kbn/core-saved-objects-base-server-internal'; diff --git a/src/core/packages/saved-objects/api-server-internal/src/test_helpers/repository.test.common.ts b/src/core/packages/saved-objects/api-server-internal/src/test_helpers/repository.test.common.ts index 2ae35750d2f0a..8682e449dfd15 100644 --- a/src/core/packages/saved-objects/api-server-internal/src/test_helpers/repository.test.common.ts +++ b/src/core/packages/saved-objects/api-server-internal/src/test_helpers/repository.test.common.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { loggerMock } from '@kbn/logging-mocks'; import type { Payload } from 'elastic-apm-node'; diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/bulk_overwrite_transformed_documents.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/bulk_overwrite_transformed_documents.ts index fa5ab8e09b3d6..776cb96512f36 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/bulk_overwrite_transformed_documents.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/bulk_overwrite_transformed_documents.ts @@ -9,7 +9,7 @@ import * as Either from 'fp-ts/lib/Either'; import * as TaskEither from 'fp-ts/lib/TaskEither'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { errors as esErrors } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import { diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/close_pit.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/close_pit.ts index 3cdf045c82c77..12eb8a0792027 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/close_pit.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/close_pit.ts @@ -28,9 +28,7 @@ export const closePit = ({ client, pitId }: ClosePitParams): TaskEither.TaskEither => () => { return client - .closePointInTime({ - body: { id: pitId }, - }) + .closePointInTime({ id: pitId }) .then((response) => { if (!response.succeeded) { throw new Error(`Failed to close PointInTime with id: ${pitId}`); diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/create_index.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/create_index.ts index 5895f6b1cca0a..589d9b4cb1577 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/create_index.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/create_index.ts @@ -10,7 +10,7 @@ import * as Either from 'fp-ts/lib/Either'; import * as TaskEither from 'fp-ts/lib/TaskEither'; import { pipe } from 'fp-ts/lib/function'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient, ElasticsearchCapabilities, diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/read_with_pit.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/read_with_pit.ts index 283786a4d90f5..666b47d8a62bf 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/read_with_pit.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/read_with_pit.ts @@ -9,7 +9,7 @@ import * as Either from 'fp-ts/lib/Either'; import * as TaskEither from 'fp-ts/lib/TaskEither'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { errors as EsErrors } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import type { SavedObjectsRawDoc } from '@kbn/core-saved-objects-server'; diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.test.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.test.ts index 862acd1d2ae5c..eeb4b5e7fa340 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.test.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.test.ts @@ -73,22 +73,21 @@ describe('reindex', () => { /** ignore */ } expect(client.reindex).toHaveBeenCalledTimes(1); - expect(client.reindex).toHaveBeenCalledWith( - expect.objectContaining({ - body: { - conflicts: 'proceed', - source: { - index: 'my_source_index', - size: 99, - query: { match_all: {} }, - }, - dest: { - index: 'my_target_index', - op_type: 'create', - }, - script: { lang: 'painless', source: 'my script' }, - }, - }) - ); + expect(client.reindex).toHaveBeenCalledWith({ + conflicts: 'proceed', + source: { + index: 'my_source_index', + size: 99, + query: { match_all: {} }, + }, + dest: { + index: 'my_target_index', + op_type: 'create', + }, + script: { lang: 'painless', source: 'my script' }, + refresh: true, + require_alias: false, + wait_for_completion: false, + }); }); }); diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.ts index a0b4e20b7eb67..085e354a7307a 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/reindex.ts @@ -62,29 +62,27 @@ export const reindex = // Require targetIndex to be an alias. Prevents a new index from being // created if targetIndex doesn't exist. require_alias: requireAlias, - body: { - // Ignore version conflicts from existing documents - conflicts: 'proceed', - source: { - index: sourceIndex, - // Set reindex batch size - size: batchSize, - // Exclude saved object types - query: excludeOnUpgradeQuery, - }, - dest: { - index: targetIndex, - // Don't override existing documents, only create if missing - op_type: 'create', - }, - script: Option.fold( - () => undefined, - (script) => ({ - source: script, - lang: 'painless', - }) - )(reindexScript), + // Ignore version conflicts from existing documents + conflicts: 'proceed', + source: { + index: sourceIndex, + // Set reindex batch size + size: batchSize, + // Exclude saved object types + query: excludeOnUpgradeQuery, }, + dest: { + index: targetIndex, + // Don't override existing documents, only create if missing + op_type: 'create', + }, + script: Option.fold( + () => undefined, + (script) => ({ + source: script, + lang: 'painless', + }) + )(reindexScript), // force a refresh so that we can query the target index refresh: true, // Create a task and return task id instead of blocking until complete diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/wait_for_task.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/wait_for_task.ts index 304e832ea8366..483c620a44537 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/wait_for_task.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/wait_for_task.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import * as Either from 'fp-ts/lib/Either'; import * as TaskEither from 'fp-ts/lib/TaskEither'; import * as Option from 'fp-ts/lib/Option'; diff --git a/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.test.ts b/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.test.ts index ee578c5f41d4e..04b4fbc6cf96c 100644 --- a/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.test.ts +++ b/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.test.ts @@ -174,11 +174,9 @@ describe('unknown saved object types deprecation', () => { expect(esClient.asInternalUser.deleteByQuery).toHaveBeenCalledWith({ index: ['foo-index', 'bar-index'], wait_for_completion: false, - body: { - query: { - bool: { - must_not: [{ term: { type: 'foo' } }, { term: { type: 'bar' } }], - }, + query: { + bool: { + must_not: [{ term: { type: 'foo' } }, { term: { type: 'bar' } }], }, }, }); diff --git a/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.ts b/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.ts index 4dc0787167474..14a65d1934353 100644 --- a/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.ts +++ b/src/core/packages/saved-objects/server-internal/src/deprecations/unknown_object_types.ts @@ -141,8 +141,6 @@ export const deleteUnknownTypeObjects = async ({ await esClient.asInternalUser.deleteByQuery({ index: targetIndices, wait_for_completion: false, - body: { - query: nonRegisteredTypesQuery, - }, + query: nonRegisteredTypesQuery, }); }; diff --git a/src/core/packages/usage-data/server-internal/src/core_usage_data_service.ts b/src/core/packages/usage-data/server-internal/src/core_usage_data_service.ts index dec6b7fa5efd2..76af7f124ab31 100644 --- a/src/core/packages/usage-data/server-internal/src/core_usage_data_service.ts +++ b/src/core/packages/usage-data/server-internal/src/core_usage_data_service.ts @@ -182,26 +182,24 @@ export class CoreUsageDataService { aliases: UsageDataAggs } >({ index: MAIN_SAVED_OBJECT_INDEX, // depends on the .kibana split (assuming 'legacy-url-alias' is stored in '.kibana') - body: { - track_total_hits: true, - query: { match: { type: LEGACY_URL_ALIAS_TYPE } }, - aggs: { - aliases: { + track_total_hits: true, + query: { match: { type: LEGACY_URL_ALIAS_TYPE } }, + aggs: { + aliases: { + filters: { filters: { - filters: { - disabled: { term: { [`${LEGACY_URL_ALIAS_TYPE}.disabled`]: true } }, - active: { - bool: { - must_not: { term: { [`${LEGACY_URL_ALIAS_TYPE}.disabled`]: true } }, - must: { range: { [`${LEGACY_URL_ALIAS_TYPE}.resolveCounter`]: { gte: 1 } } }, - }, + disabled: { term: { [`${LEGACY_URL_ALIAS_TYPE}.disabled`]: true } }, + active: { + bool: { + must_not: { term: { [`${LEGACY_URL_ALIAS_TYPE}.disabled`]: true } }, + must: { range: { [`${LEGACY_URL_ALIAS_TYPE}.resolveCounter`]: { gte: 1 } } }, }, }, }, }, }, - size: 0, }, + size: 0, }); const { hits, aggregations } = resp; diff --git a/src/core/server/integration_tests/ci_checks/jest.integration.config.js b/src/core/server/integration_tests/ci_checks/jest.integration.config.js index 9cdb0e5c986f7..4e58d2bd7316e 100644 --- a/src/core/server/integration_tests/ci_checks/jest.integration.config.js +++ b/src/core/server/integration_tests/ci_checks/jest.integration.config.js @@ -9,11 +9,12 @@ module.exports = { bail: true, // only report 1 issue - // TODO replace the line below with - // preset: '@kbn/test/jest_integration_node + // TODO remove the line below once we've addressed all the open handles + // We stop the server very soon, and plugins installing (and retrying indices) might keep Kibana running until a timeout occurs. // to do so, we must fix all integration tests first // see https://github.com/elastic/kibana/pull/130255/ - preset: '@kbn/test/jest_integration', + forceExit: true, + preset: '@kbn/test/jest_integration_node', rootDir: '../../../../..', roots: ['/src/core/server/integration_tests/ci_checks'], // must override to match all test given there is no `integration_tests` subfolder diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts index cd138e47caafc..6bdd3156f2528 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts @@ -138,11 +138,9 @@ describe('migration actions', () => { describe('fetchIndices', () => { afterAll(async () => { await client.cluster.putSettings({ - body: { - persistent: { - // Reset persistent test settings - cluster: { routing: { allocation: { enable: null } } }, - }, + persistent: { + // Reset persistent test settings + cluster: { routing: { allocation: { enable: null } } }, }, }); }); @@ -209,11 +207,9 @@ describe('migration actions', () => { it('resolves left when cluster.routing.allocation.enabled is incompatible', async () => { expect.assertions(3); await client.cluster.putSettings({ - body: { - persistent: { - // Disable all routing allocation - cluster: { routing: { allocation: { enable: 'none' } } }, - }, + persistent: { + // Disable all routing allocation + cluster: { routing: { allocation: { enable: 'none' } } }, }, }); const task = checkClusterRoutingAllocationEnabled(client); @@ -226,11 +222,9 @@ describe('migration actions', () => { } `); await client.cluster.putSettings({ - body: { - persistent: { - // Allow routing to existing primaries only - cluster: { routing: { allocation: { enable: 'primaries' } } }, - }, + persistent: { + // Allow routing to existing primaries only + cluster: { routing: { allocation: { enable: 'primaries' } } }, }, }); const task2 = checkClusterRoutingAllocationEnabled(client); @@ -243,11 +237,9 @@ describe('migration actions', () => { } `); await client.cluster.putSettings({ - body: { - persistent: { - // Allow routing to new primaries only - cluster: { routing: { allocation: { enable: 'new_primaries' } } }, - }, + persistent: { + // Allow routing to new primaries only + cluster: { routing: { allocation: { enable: 'new_primaries' } } }, }, }); const task3 = checkClusterRoutingAllocationEnabled(client); @@ -263,10 +255,8 @@ describe('migration actions', () => { it('resolves right when cluster.routing.allocation.enabled=all', async () => { expect.assertions(1); await client.cluster.putSettings({ - body: { - persistent: { - cluster: { routing: { allocation: { enable: 'all' } } }, - }, + persistent: { + cluster: { routing: { allocation: { enable: 'all' } } }, }, }); const task = checkClusterRoutingAllocationEnabled(client); @@ -398,14 +388,12 @@ describe('migration actions', () => { await client.indices.create({ index: 'red_then_yellow_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - // Disable all shard allocation so that the index status is red - routing: { allocation: { enable: 'none' } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', + // Disable all shard allocation so that the index status is red + routing: { allocation: { enable: 'none' } }, }, }); @@ -421,7 +409,7 @@ describe('migration actions', () => { void client.indices.putSettings({ index: 'red_then_yellow_index', - body: { + settings: { // Enable all shard allocation so that the index status turns yellow routing: { allocation: { enable: 'all' } }, }, @@ -439,14 +427,12 @@ describe('migration actions', () => { .create({ index: 'red_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate no replicas so that this index stays red - number_of_replicas: '0', - // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate no replicas so that this index stays red + number_of_replicas: '0', + // Disable all shard allocation so that the index status is red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => {}); @@ -474,12 +460,10 @@ describe('migration actions', () => { .create({ index: 'yellow_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate no replicas so that this index stays yellow - number_of_replicas: '0', - }, + mappings: { properties: {} }, + settings: { + // Allocate no replicas so that this index stays yellow + number_of_replicas: '0', }, }) .catch((e) => {}); @@ -546,14 +530,12 @@ describe('migration actions', () => { .create({ index: 'clone_red_then_green_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index can go to green - number_of_replicas: '0', - // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index can go to green + number_of_replicas: '0', + // Disable all shard allocation so that the index status is red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => {}); @@ -570,7 +552,7 @@ describe('migration actions', () => { setTimeout(() => { void client.indices.putSettings({ index: 'clone_red_then_green_index', - body: { + settings: { // Enable all shard allocation so that the index status goes green routing: { allocation: { enable: 'all' } }, }, @@ -598,14 +580,12 @@ describe('migration actions', () => { .create({ index: 'clone_red_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', + // Disable all shard allocation so that the index status is red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => {}); @@ -633,7 +613,7 @@ describe('migration actions', () => { await client.indices.putSettings({ index: 'clone_red_index', - body: { + settings: { // Enable all shard allocation so that the index status goes yellow routing: { allocation: { enable: 'all' } }, }, @@ -662,7 +642,7 @@ describe('migration actions', () => { await client.indices.putSettings({ index: 'clone_red_index', - body: { + settings: { // Set zero replicas so status goes green number_of_replicas: 0, }, @@ -1126,11 +1106,7 @@ describe('migration actions', () => { expect(pitResponse.right.pitId).toEqual(expect.any(String)); - const searchResponse = await client.search({ - body: { - pit: { id: pitResponse.right.pitId }, - }, - }); + const searchResponse = await client.search({ pit: { id: pitResponse.right.pitId } }); await expect(searchResponse.hits.hits.length).toBeGreaterThan(0); }); @@ -1346,11 +1322,7 @@ describe('migration actions', () => { const pitId = pitResponse.right.pitId; await closePit({ client, pitId })(); - const searchTask = client.search({ - body: { - pit: { id: pitId }, - }, - }); + const searchTask = client.search({ pit: { id: pitId } }); await expect(searchTask).rejects.toThrow('search_phase_execution_exception'); }); @@ -1811,14 +1783,12 @@ describe('migration actions', () => { .create({ index: 'red_then_yellow_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - // Disable all shard allocation so that the index status starts as red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', + // Disable all shard allocation so that the index status starts as red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => { @@ -1840,7 +1810,7 @@ describe('migration actions', () => { setTimeout(() => { void client.indices.putSettings({ index: 'red_then_yellow_index', - body: { + settings: { // Renable allocation so that the status becomes yellow routing: { allocation: { enable: 'all' } }, }, @@ -1869,12 +1839,10 @@ describe('migration actions', () => { .create({ index: 'yellow_then_green_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', }, }) .catch((e) => { @@ -1893,7 +1861,7 @@ describe('migration actions', () => { setTimeout(() => { void client.indices.putSettings({ index: 'yellow_then_green_index', - body: { + settings: { // Set 0 replican so that this index becomes green number_of_replicas: '0', }, diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts index 1bf2d5d0d7e6a..edb9299378efc 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts @@ -176,11 +176,9 @@ export const runActionTestSuite = ({ describe('fetchIndices', () => { afterAll(async () => { await client.cluster.putSettings({ - body: { - persistent: { - // Reset persistent test settings - cluster: { routing: { allocation: { enable: null } } }, - }, + persistent: { + // Reset persistent test settings + cluster: { routing: { allocation: { enable: null } } }, }, }); }); @@ -247,11 +245,9 @@ export const runActionTestSuite = ({ it('resolves left when cluster.routing.allocation.enabled is incompatible', async () => { expect.assertions(3); await client.cluster.putSettings({ - body: { - persistent: { - // Disable all routing allocation - cluster: { routing: { allocation: { enable: 'none' } } }, - }, + persistent: { + // Disable all routing allocation + cluster: { routing: { allocation: { enable: 'none' } } }, }, }); const task = checkClusterRoutingAllocationEnabled(client); @@ -264,11 +260,9 @@ export const runActionTestSuite = ({ } `); await client.cluster.putSettings({ - body: { - persistent: { - // Allow routing to existing primaries only - cluster: { routing: { allocation: { enable: 'primaries' } } }, - }, + persistent: { + // Allow routing to existing primaries only + cluster: { routing: { allocation: { enable: 'primaries' } } }, }, }); const task2 = checkClusterRoutingAllocationEnabled(client); @@ -281,11 +275,9 @@ export const runActionTestSuite = ({ } `); await client.cluster.putSettings({ - body: { - persistent: { - // Allow routing to new primaries only - cluster: { routing: { allocation: { enable: 'new_primaries' } } }, - }, + persistent: { + // Allow routing to new primaries only + cluster: { routing: { allocation: { enable: 'new_primaries' } } }, }, }); const task3 = checkClusterRoutingAllocationEnabled(client); @@ -301,10 +293,8 @@ export const runActionTestSuite = ({ it('resolves right when cluster.routing.allocation.enabled=all', async () => { expect.assertions(1); await client.cluster.putSettings({ - body: { - persistent: { - cluster: { routing: { allocation: { enable: 'all' } } }, - }, + persistent: { + cluster: { routing: { allocation: { enable: 'all' } } }, }, }); const task = checkClusterRoutingAllocationEnabled(client); @@ -436,14 +426,12 @@ export const runActionTestSuite = ({ { index: 'red_then_yellow_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - // Disable all shard allocation so that the index status is red - routing: { allocation: { enable: 'none' } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', + // Disable all shard allocation so that the index status is red + routing: { allocation: { enable: 'none' } }, }, }, { maxRetries: 0 /** handle retry ourselves for now */ } @@ -461,7 +449,7 @@ export const runActionTestSuite = ({ void client.indices.putSettings({ index: 'red_then_yellow_index', - body: { + settings: { // Enable all shard allocation so that the index status turns yellow routing: { allocation: { enable: 'all' } }, }, @@ -483,14 +471,12 @@ export const runActionTestSuite = ({ .create({ index: 'red_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate no replicas so that this index stays red - number_of_replicas: '0', - // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate no replicas so that this index stays red + number_of_replicas: '0', + // Disable all shard allocation so that the index status is red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => {}); @@ -518,12 +504,10 @@ export const runActionTestSuite = ({ .create({ index: 'yellow_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate no replicas so that this index stays yellow - number_of_replicas: '0', - }, + mappings: { properties: {} }, + settings: { + // Allocate no replicas so that this index stays yellow + number_of_replicas: '0', }, }) .catch((e) => {}); @@ -580,8 +564,7 @@ export const runActionTestSuite = ({ const { clone_target_1: cloneTarget1 } = await client.indices.getSettings({ index: 'clone_target_1', }); - // @ts-expect-error https://github.com/elastic/elasticsearch/issues/89381 - expect(cloneTarget1.settings?.index.mapping?.total_fields.limit).toBe('1500'); + expect(cloneTarget1.settings?.index?.mapping?.total_fields?.limit).toBe('1500'); expect(cloneTarget1.settings?.blocks?.write).toBeUndefined(); }); it('resolves right if clone target already existed after waiting for index status to be green ', async () => { @@ -592,14 +575,12 @@ export const runActionTestSuite = ({ .create({ index: 'clone_red_then_green_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index can go to green - number_of_replicas: '0', - // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index can go to green + number_of_replicas: '0', + // Disable all shard allocation so that the index status is red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => {}); @@ -616,7 +597,7 @@ export const runActionTestSuite = ({ setTimeout(() => { void client.indices.putSettings({ index: 'clone_red_then_green_index', - body: { + settings: { // Enable all shard allocation so that the index status goes green routing: { allocation: { enable: 'all' } }, }, @@ -644,14 +625,12 @@ export const runActionTestSuite = ({ .create({ index: 'clone_red_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', + // Disable all shard allocation so that the index status is red + index: { routing: { allocation: { enable: 'none' } } }, }, }) .catch((e) => {}); @@ -679,7 +658,7 @@ export const runActionTestSuite = ({ await client.indices.putSettings({ index: 'clone_red_index', - body: { + settings: { // Enable all shard allocation so that the index status goes yellow routing: { allocation: { enable: 'all' } }, }, @@ -708,7 +687,7 @@ export const runActionTestSuite = ({ await client.indices.putSettings({ index: 'clone_red_index', - body: { + settings: { // Set zero replicas so status goes green number_of_replicas: 0, }, @@ -1178,11 +1157,7 @@ export const runActionTestSuite = ({ expect(pitResponse.right.pitId).toEqual(expect.any(String)); - const searchResponse = await client.search({ - body: { - pit: { id: pitResponse.right.pitId }, - }, - }); + const searchResponse = await client.search({ pit: { id: pitResponse.right.pitId } }); await expect(searchResponse.hits.hits.length).toBeGreaterThan(0); }); @@ -1398,11 +1373,7 @@ export const runActionTestSuite = ({ const pitId = pitResponse.right.pitId; await closePit({ client, pitId })(); - const searchTask = client.search({ - body: { - pit: { id: pitId }, - }, - }); + const searchTask = client.search({ pit: { id: pitId } }); await expect(searchTask).rejects.toThrow('search_phase_execution_exception'); }); @@ -1867,14 +1838,12 @@ export const runActionTestSuite = ({ { index: 'red_then_yellow_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - // Disable all shard allocation so that the index status starts as red - index: { routing: { allocation: { enable: 'none' } } }, - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', + // Disable all shard allocation so that the index status starts as red + index: { routing: { allocation: { enable: 'none' } } }, }, }, { maxRetries: 0 /** handle retry ourselves for now */ } @@ -1895,7 +1864,7 @@ export const runActionTestSuite = ({ setTimeout(() => { void client.indices.putSettings({ index: 'red_then_yellow_index', - body: { + settings: { // Renable allocation so that the status becomes yellow routing: { allocation: { enable: 'all' } }, }, @@ -1924,12 +1893,10 @@ export const runActionTestSuite = ({ .create({ index: 'yellow_then_green_index', timeout: '5s', - body: { - mappings: { properties: {} }, - settings: { - // Allocate 1 replica so that this index stays yellow - number_of_replicas: '1', - }, + mappings: { properties: {} }, + settings: { + // Allocate 1 replica so that this index stays yellow + number_of_replicas: '1', }, }) .catch((e) => { @@ -1948,7 +1915,7 @@ export const runActionTestSuite = ({ setTimeout(() => { void client.indices.putSettings({ index: 'yellow_then_green_index', - body: { + settings: { // Set 0 replican so that this index becomes green number_of_replicas: '0', }, diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/es_errors.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/es_errors.test.ts index a0d725324d9a1..c67f6b17acd9a 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/es_errors.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/es_errors.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { InternalCoreStart } from '@kbn/core-lifecycle-server-internal'; import { Root } from '@kbn/core-root-server-internal'; import { elasticsearchServiceMock } from '@kbn/core-elasticsearch-server-mocks'; @@ -68,7 +68,7 @@ describe('Elasticsearch Errors', () => { index: 'existing_index_with_write_block', id: 'some-id', op_type: 'index', - body: { + document: { hello: 'dolly', }, }, @@ -98,7 +98,7 @@ describe('Elasticsearch Errors', () => { it('correctly identify errors from bulk index operations', async () => { const res = await client.bulk({ refresh: 'wait_for', - body: [ + operations: [ { index: { _index: 'existing_index_with_write_block', @@ -119,7 +119,7 @@ describe('Elasticsearch Errors', () => { it('correctly identify errors from bulk create operations', async () => { const res = await client.bulk({ refresh: 'wait_for', - body: [ + operations: [ { create: { _index: 'existing_index_with_write_block', diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/multiple_es_nodes.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/multiple_es_nodes.test.ts index 6898962077b9c..75c43038c2744 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/multiple_es_nodes.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/multiple_es_nodes.test.ts @@ -38,15 +38,13 @@ async function fetchDocs(esClient: ElasticsearchClient, index: string, type: str const body = await esClient.search({ index, size: 10000, - body: { - query: { - bool: { - should: [ - { - term: { type }, - }, - ], - }, + query: { + bool: { + should: [ + { + term: { type }, + }, + ], }, }, }); diff --git a/src/core/server/integration_tests/saved_objects/migrations/zdt_2/outdated_doc_query.test.ts b/src/core/server/integration_tests/saved_objects/migrations/zdt_2/outdated_doc_query.test.ts index 59b35638de94f..da41ce206332b 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/zdt_2/outdated_doc_query.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/zdt_2/outdated_doc_query.test.ts @@ -102,7 +102,7 @@ describe('getOutdatedDocumentsQuery', () => { await client.bulk({ refresh: 'true', - body: bulkCreateParams, + operations: bulkCreateParams, }); return { client }; diff --git a/src/core/server/integration_tests/saved_objects/routes/delete_unknown_types.test.ts b/src/core/server/integration_tests/saved_objects/routes/delete_unknown_types.test.ts index 878af4428b159..6f511b6bf07f7 100644 --- a/src/core/server/integration_tests/saved_objects/routes/delete_unknown_types.test.ts +++ b/src/core/server/integration_tests/saved_objects/routes/delete_unknown_types.test.ts @@ -75,11 +75,9 @@ describe('POST /internal/saved_objects/deprecations/_delete_unknown_types', () = expect(elasticsearchClient.asInternalUser.deleteByQuery).toHaveBeenCalledWith({ index: ['known-type-index_8.0.0'], wait_for_completion: false, - body: { - query: { - bool: { - must_not: expect.any(Array), - }, + query: { + bool: { + must_not: expect.any(Array), }, }, }); diff --git a/src/core/server/integration_tests/ui_settings/doc_exists.ts b/src/core/server/integration_tests/ui_settings/doc_exists.ts index 686a34bfcfb6f..10745dff123dd 100644 --- a/src/core/server/integration_tests/ui_settings/doc_exists.ts +++ b/src/core/server/integration_tests/ui_settings/doc_exists.ts @@ -24,9 +24,7 @@ export const docExistsSuite = (savedObjectsIndex: string) => () => { await esClient.deleteByQuery({ index: savedObjectsIndex, conflicts: 'proceed', - body: { - query: { match_all: {} }, - }, + query: { match_all: {} }, refresh: true, wait_for_completion: true, }); diff --git a/src/core/server/integration_tests/ui_settings/doc_missing.ts b/src/core/server/integration_tests/ui_settings/doc_missing.ts index b80b596013805..4e54220ae43d6 100644 --- a/src/core/server/integration_tests/ui_settings/doc_missing.ts +++ b/src/core/server/integration_tests/ui_settings/doc_missing.ts @@ -19,9 +19,7 @@ export const docMissingSuite = (savedObjectsIndex: string) => () => { // delete all docs from kibana index to ensure savedConfig is not found await esClient.deleteByQuery({ index: savedObjectsIndex, - body: { - query: { match_all: {} }, - }, + query: { match_all: {} }, }); }); diff --git a/src/core/test-helpers/kbn-server/src/create_serverless_root.ts b/src/core/test-helpers/kbn-server/src/create_serverless_root.ts index e14e2ecd9d1b0..f0aa58eb9d79c 100644 --- a/src/core/test-helpers/kbn-server/src/create_serverless_root.ts +++ b/src/core/test-helpers/kbn-server/src/create_serverless_root.ts @@ -116,6 +116,7 @@ const getServerlessESClient = ({ port }: { port: number }) => { return new Client({ node: `http://localhost:${port}`, Connection: HttpConnection, + requestTimeout: 30_000, auth: { ...systemIndicesSuperuser }, }); }; diff --git a/src/dev/code_coverage/ingest_coverage/ingest.js b/src/dev/code_coverage/ingest_coverage/ingest.js index bc43304ece46a..09ae98310273b 100644 --- a/src/dev/code_coverage/ingest_coverage/ingest.js +++ b/src/dev/code_coverage/ingest_coverage/ingest.js @@ -28,11 +28,11 @@ export const ingestList = (log) => async (xs) => { async function bulkIngest() { log.verbose(`\n${ccMark} Ingesting ${xs.length} docs at a time`); - const body = parseIndexes(xs); + const operations = parseIndexes(xs); - const bulkResponse = await client.bulk({ refresh: true, body }); + const bulkResponse = await client.bulk({ refresh: true, operations }); - handleErrors(body, bulkResponse)(log); + handleErrors(operations, bulkResponse)(log); } }; diff --git a/src/dev/precommit_hook/casing_check_config.js b/src/dev/precommit_hook/casing_check_config.js index d193ee3875a70..895e184bbfdf7 100644 --- a/src/dev/precommit_hook/casing_check_config.js +++ b/src/dev/precommit_hook/casing_check_config.js @@ -102,6 +102,7 @@ export const KEBAB_CASE_DIRECTORY_GLOBS = [ 'packages/*', 'x-pack', 'x-pack/packages/*', + 'src/dev/packages/*', 'src/core/packages/*/*', 'src/platform/packages/private/*', 'src/platform/packages/shared/*', diff --git a/src/platform/packages/private/kbn-generate-csv/src/generate_csv.test.ts b/src/platform/packages/private/kbn-generate-csv/src/generate_csv.test.ts index 2147e6e50c56a..badbb5eb0d366 100644 --- a/src/platform/packages/private/kbn-generate-csv/src/generate_csv.test.ts +++ b/src/platform/packages/private/kbn-generate-csv/src/generate_csv.test.ts @@ -377,7 +377,7 @@ describe('CsvGenerator', () => { expect(mockDataClient.search).toHaveBeenCalledTimes(10); expect(mockDataClient.search).toBeCalledWith( - { params: { body: {}, ignore_throttled: undefined, max_concurrent_shard_requests: 5 } }, + { params: { max_concurrent_shard_requests: 5 } }, { abortSignal: expect.any(AbortSignal), strategy: 'es', @@ -402,7 +402,7 @@ describe('CsvGenerator', () => { expect(mockEsClient.asCurrentUser.closePointInTime).toHaveBeenCalledTimes(1); expect(mockEsClient.asCurrentUser.closePointInTime).toHaveBeenCalledWith({ - body: { id: mockCursorId }, + id: mockCursorId, }); }); @@ -676,7 +676,7 @@ describe('CsvGenerator', () => { ); expect(mockDataClientSearchFn).toBeCalledWith( - { params: { body: {}, ignore_throttled: undefined, max_concurrent_shard_requests: 5 } }, + { params: { max_concurrent_shard_requests: 5 } }, { abortSignal: expect.any(AbortSignal), strategy: 'es', @@ -762,7 +762,7 @@ describe('CsvGenerator', () => { ); expect(mockDataClientSearchFn).toBeCalledWith( - { params: { body: {}, ignore_throttled: undefined, max_concurrent_shard_requests: 5 } }, + { params: { max_concurrent_shard_requests: 5 } }, { abortSignal: expect.any(AbortSignal), strategy: 'es', @@ -1439,7 +1439,6 @@ describe('CsvGenerator', () => { expect(mockDataClient.search).toBeCalledWith( { params: { - body: {}, max_concurrent_shard_requests: 5, }, }, diff --git a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.test.ts b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.test.ts index ab5e294397a6e..f69fabb6e214c 100644 --- a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.test.ts +++ b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.test.ts @@ -101,10 +101,10 @@ describe('CSV Export Search Cursor', () => { expect(dataSearchSpy).toBeCalledTimes(1); expect(dataSearchSpy).toBeCalledWith( { - params: { - body: expect.objectContaining({ pit: { id: 'somewhat-pit-id', keep_alive: '10m' } }), + params: expect.objectContaining({ + pit: { id: 'somewhat-pit-id', keep_alive: '10m' }, max_concurrent_shard_requests: 5, - }, + }), }, expect.objectContaining({ strategy: 'es', @@ -160,14 +160,12 @@ describe('CSV Export Search Cursor', () => { expect(dataSearchSpy).toBeCalledWith( { params: { - body: { - fields: [], - pit: { id: 'somewhat-pit-id', keep_alive: '10m' }, - query: { bool: { filter: [], must: [], must_not: [], should: [] } }, - runtime_mappings: {}, - script_fields: {}, - stored_fields: ['*'], - }, + fields: [], + pit: { id: 'somewhat-pit-id', keep_alive: '10m' }, + query: { bool: { filter: [], must: [], must_not: [], should: [] } }, + runtime_mappings: {}, + script_fields: {}, + stored_fields: ['*'], max_concurrent_shard_requests: undefined, }, }, diff --git a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.ts b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.ts index 03b2a12909643..75f7434246192 100644 --- a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.ts +++ b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.ts @@ -80,7 +80,7 @@ export class SearchCursorPit extends SearchCursor { const searchParamsPit = { params: { - body: searchBody, + ...searchBody, max_concurrent_shard_requests: effectiveMaxConcurrentShardRequests, }, }; @@ -164,7 +164,7 @@ export class SearchCursorPit extends SearchCursor { public async closeCursor() { if (this.cursorId) { this.logger.debug(`Executing close PIT on ${this.formatCursorId(this.cursorId)}`); - await this.clients.es.asCurrentUser.closePointInTime({ body: { id: this.cursorId } }); + await this.clients.es.asCurrentUser.closePointInTime({ id: this.cursorId }); } else { this.logger.warn(`No PIT Id to clear!`); } diff --git a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.test.ts b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.test.ts index cdccbca468a76..b79271b5cebd9 100644 --- a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.test.ts +++ b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.test.ts @@ -80,13 +80,11 @@ describe('CSV Export Search Cursor', () => { expect(dataSearchSpy).toBeCalledWith( { params: { - body: { - fields: [], - query: { bool: { filter: [], must: [], must_not: [], should: [] } }, - runtime_mappings: {}, - script_fields: {}, - stored_fields: ['*'], - }, + fields: [], + query: { bool: { filter: [], must: [], must_not: [], should: [] } }, + runtime_mappings: {}, + script_fields: {}, + stored_fields: ['*'], ignore_throttled: undefined, index: 'test-index-pattern-string', max_concurrent_shard_requests: 5, @@ -135,13 +133,11 @@ describe('CSV Export Search Cursor', () => { expect(dataSearchSpy).toBeCalledWith( { params: { - body: { - fields: [], - query: { bool: { filter: [], must: [], must_not: [], should: [] } }, - runtime_mappings: {}, - script_fields: {}, - stored_fields: ['*'], - }, + fields: [], + query: { bool: { filter: [], must: [], must_not: [], should: [] } }, + runtime_mappings: {}, + script_fields: {}, + stored_fields: ['*'], ignore_throttled: undefined, index: 'test-index-pattern-string', max_concurrent_shard_requests: undefined, diff --git a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.ts b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.ts index 835f6f02e7322..06b0ec0106f9f 100644 --- a/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.ts +++ b/src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_scroll.ts @@ -38,7 +38,7 @@ export class SearchCursorScroll extends SearchCursor { const searchParamsScan = { params: { - body: searchBody, + ...searchBody, index: this.indexPatternTitle, scroll: scroll.duration(taskInstanceFields), size: scroll.size, diff --git a/src/platform/packages/private/kbn-scout-reporting/src/helpers/elasticsearch.ts b/src/platform/packages/private/kbn-scout-reporting/src/helpers/elasticsearch.ts index d49b1b8244c26..7ee1181547afe 100644 --- a/src/platform/packages/private/kbn-scout-reporting/src/helpers/elasticsearch.ts +++ b/src/platform/packages/private/kbn-scout-reporting/src/helpers/elasticsearch.ts @@ -7,7 +7,11 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client as ESClient, ClientOptions as ESClientOptions } from '@elastic/elasticsearch'; +import { + Client as ESClient, + ClientOptions as ESClientOptions, + HttpConnection, +} from '@elastic/elasticsearch'; import { ToolingLog } from '@kbn/tooling-log'; import { createFailError } from '@kbn/dev-cli-errors'; @@ -28,7 +32,11 @@ export async function getValidatedESClient( } ): Promise { const { log, cli = false } = helperSettings; - const es = new ESClient(esClientOptions); + const es = new ESClient({ + Connection: HttpConnection, + requestTimeout: 30_000, + ...esClientOptions, + }); try { const esInfo = await es.info(); diff --git a/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/hooks/use_get_alerts_group_aggregations_query.ts b/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/hooks/use_get_alerts_group_aggregations_query.ts index e3c2d42a391e9..c0b022578d7be 100644 --- a/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/hooks/use_get_alerts_group_aggregations_query.ts +++ b/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/hooks/use_get_alerts_group_aggregations_query.ts @@ -16,7 +16,7 @@ import type { AggregationsAggregationContainer, QueryDslQueryContainer, SortCombinations, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { BASE_RAC_ALERTS_API_PATH } from '../constants'; export interface UseGetAlertsGroupAggregationsQueryProps { diff --git a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_apm_es_client.ts b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_apm_es_client.ts index 5a767dbb113fc..90833654a81e3 100644 --- a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_apm_es_client.ts +++ b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_apm_es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { ApmSynthtraceEsClient } from '../../..'; import { Logger } from '../../lib/utils/create_logger'; import { RunOptions } from './parse_run_cli_flags'; @@ -26,6 +26,8 @@ export function getApmEsClient({ const client = new Client({ node: target, tls: getEsClientTlsSettings(target), + Connection: HttpConnection, + requestTimeout: 30_000, }); const apmEsClient = new ApmSynthtraceEsClient({ diff --git a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_entities_es_client.ts b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_entities_es_client.ts index b52908b470551..e9ced638b571c 100644 --- a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_entities_es_client.ts +++ b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_entities_es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { EntitiesSynthtraceEsClient } from '../../lib/entities/entities_synthtrace_es_client'; import { Logger } from '../../lib/utils/create_logger'; import { RunOptions } from './parse_run_cli_flags'; @@ -24,6 +24,8 @@ export function getEntitiesEsClient({ const client = new Client({ node: target, tls: getEsClientTlsSettings(target), + Connection: HttpConnection, + requestTimeout: 30_000, }); return new EntitiesSynthtraceEsClient({ diff --git a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_infra_es_client.ts b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_infra_es_client.ts index 1ebf568a5b497..00ebedbfb1791 100644 --- a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_infra_es_client.ts +++ b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_infra_es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { InfraSynthtraceEsClient } from '../../lib/infra/infra_synthtrace_es_client'; import { Logger } from '../../lib/utils/create_logger'; import { RunOptions } from './parse_run_cli_flags'; @@ -24,6 +24,8 @@ export function getInfraEsClient({ const client = new Client({ node: target, tls: getEsClientTlsSettings(target), + Connection: HttpConnection, + requestTimeout: 30_000, }); return new InfraSynthtraceEsClient({ diff --git a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_logs_es_client.ts b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_logs_es_client.ts index ac42f738a1531..75603c94eb0b6 100644 --- a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_logs_es_client.ts +++ b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_logs_es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { LogsSynthtraceEsClient } from '../../lib/logs/logs_synthtrace_es_client'; import { Logger } from '../../lib/utils/create_logger'; import { RunOptions } from './parse_run_cli_flags'; @@ -24,6 +24,8 @@ export function getLogsEsClient({ const client = new Client({ node: target, tls: getEsClientTlsSettings(target), + Connection: HttpConnection, + requestTimeout: 30_000, }); return new LogsSynthtraceEsClient({ diff --git a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_otel_es_client.ts b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_otel_es_client.ts index 0671ea66c472f..236ad2812ef44 100644 --- a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_otel_es_client.ts +++ b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_otel_es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { Logger } from '../../lib/utils/create_logger'; import { RunOptions } from './parse_run_cli_flags'; import { getEsClientTlsSettings } from './ssl'; @@ -24,6 +24,8 @@ export function getOtelSynthtraceEsClient({ const client = new Client({ node: target, tls: getEsClientTlsSettings(target), + Connection: HttpConnection, + requestTimeout: 30_000, }); return new OtelSynthtraceEsClient({ diff --git a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts index c54cd847dff7a..bb78980f9ad2b 100644 --- a/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts +++ b/src/platform/packages/shared/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { Logger } from '../../lib/utils/create_logger'; import { RunOptions } from './parse_run_cli_flags'; import { getEsClientTlsSettings } from './ssl'; @@ -24,6 +24,8 @@ export function getSyntheticsEsClient({ const client = new Client({ node: target, tls: getEsClientTlsSettings(target), + Connection: HttpConnection, + requestTimeout: 30_000, }); return new SyntheticsSynthtraceEsClient({ diff --git a/src/platform/packages/shared/kbn-content-management-utils/src/types.ts b/src/platform/packages/shared/kbn-content-management-utils/src/types.ts index 2755f7f3eaa0d..3a6c286a404aa 100644 --- a/src/platform/packages/shared/kbn-content-management-utils/src/types.ts +++ b/src/platform/packages/shared/kbn-content-management-utils/src/types.ts @@ -33,7 +33,7 @@ import type { SortOrder, AggregationsAggregationContainer, SortResults, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { MutatingOperationRefreshSetting, diff --git a/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.test.ts b/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.test.ts index 5e93b92ec1a27..14264979cfe40 100644 --- a/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.test.ts +++ b/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.test.ts @@ -9,7 +9,7 @@ import { tabifyDocs, flattenHit } from './tabify_docs'; import { DataView } from '@kbn/data-views-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fieldFormatsMock } from '@kbn/field-formats-plugin/common/mocks'; import { stubbedSavedObjectIndexPattern } from '@kbn/data-views-plugin/common/data_view.stub'; diff --git a/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.ts b/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.ts index 8c877f02d4700..9380d8318d42f 100644 --- a/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.ts +++ b/src/platform/packages/shared/kbn-data-service/src/search/tabify/tabify_docs.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPlainObject } from 'lodash'; import { Datatable, diff --git a/src/platform/packages/shared/kbn-data-view-utils/src/utils/convert_to_data_view_field_spec.ts b/src/platform/packages/shared/kbn-data-view-utils/src/utils/convert_to_data_view_field_spec.ts index f853e6ad006d2..369a6b79d56e2 100644 --- a/src/platform/packages/shared/kbn-data-view-utils/src/utils/convert_to_data_view_field_spec.ts +++ b/src/platform/packages/shared/kbn-data-view-utils/src/utils/convert_to_data_view_field_spec.ts @@ -8,7 +8,7 @@ */ import type { DatatableColumn } from '@kbn/expressions-plugin/common'; -import type { MappingTimeSeriesMetricType } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTimeSeriesMetricType } from '@elastic/elasticsearch/lib/api/types'; import type { FieldSpec } from '@kbn/data-views-plugin/common'; /** diff --git a/src/platform/packages/shared/kbn-discover-utils/src/types.ts b/src/platform/packages/shared/kbn-discover-utils/src/types.ts index caf38ea0935ed..af96cc6dd7175 100644 --- a/src/platform/packages/shared/kbn-discover-utils/src/types.ts +++ b/src/platform/packages/shared/kbn-discover-utils/src/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import type { DatatableColumnMeta } from '@kbn/expressions-plugin/common'; export type { IgnoredReason, ShouldShowFieldInTableHandler } from './utils'; diff --git a/src/platform/packages/shared/kbn-discover-utils/src/utils/get_ignored_reason.ts b/src/platform/packages/shared/kbn-discover-utils/src/utils/get_ignored_reason.ts index b478d9075f085..53b3678f3775b 100644 --- a/src/platform/packages/shared/kbn-discover-utils/src/utils/get_ignored_reason.ts +++ b/src/platform/packages/shared/kbn-discover-utils/src/utils/get_ignored_reason.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { KBN_FIELD_TYPES } from '@kbn/field-types'; import type { DataViewField } from '@kbn/data-views-plugin/public'; diff --git a/src/platform/packages/shared/kbn-es-archiver/src/cli.ts b/src/platform/packages/shared/kbn-es-archiver/src/cli.ts index 71ff396c79c64..3a3f25c295e3d 100644 --- a/src/platform/packages/shared/kbn-es-archiver/src/cli.ts +++ b/src/platform/packages/shared/kbn-es-archiver/src/cli.ts @@ -110,6 +110,7 @@ export function runCli() { node: esUrl, tls: esCa ? { ca: esCa } : undefined, Connection: HttpConnection, + requestTimeout: 30_000, }); addCleanupTask(() => client.close()); diff --git a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts index 8800cfabb8872..999a231706885 100644 --- a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts +++ b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts @@ -109,7 +109,7 @@ export const createStubClient = ( return { statusCode: 404 }; }), - updateAliases: sinon.spy(async ({ body }) => { + updateAliases: sinon.spy(async (body) => { body.actions.forEach( ({ add: { index, alias } }: { add: { index: string; alias: string } }) => { if (!existingIndices.includes(index)) { diff --git a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts index c4a9749bde0c5..da2b292d1b73b 100644 --- a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts +++ b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts @@ -141,16 +141,12 @@ describe('esArchiver: createCreateIndexStream()', () => { sinon.assert.calledWith(client.indices.create as sinon.SinonSpy, { index: 'index', - body: { - settings: undefined, - mappings: undefined, - }, + settings: undefined, + mappings: undefined, }); sinon.assert.calledWith(client.indices.updateAliases as sinon.SinonSpy, { - body: { - actions: [{ add: { alias: 'foo', index: 'index' } }], - }, + actions: [{ add: { alias: 'foo', index: 'index' } }], }); }); @@ -343,9 +339,10 @@ describe('esArchiver: createCreateIndexStream()', () => { // only update aliases for the 'new-index' sinon.assert.callCount(client.indices.updateAliases as sinon.SinonSpy, 1); - expect((client.indices.updateAliases as sinon.SinonSpy).args[0][0]).toHaveProperty('body', { - actions: [{ add: { alias: 'new-index-alias', index: 'new-index' } }], - }); + expect((client.indices.updateAliases as sinon.SinonSpy).args[0][0]).toHaveProperty( + 'actions', + [{ add: { alias: 'new-index-alias', index: 'new-index' } }] + ); }); it('filters documents for skipped indices', async () => { diff --git a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.ts b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.ts index c41ff3a399797..941cbfea5ee7a 100644 --- a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.ts +++ b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/create_index_stream.ts @@ -10,7 +10,7 @@ import { Transform, Readable } from 'stream'; import { inspect } from 'util'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { Client } from '@elastic/elasticsearch'; import { ToolingLog } from '@kbn/tooling-log'; @@ -162,10 +162,8 @@ export function createCreateIndexStream({ await client.indices.create( { index, - body: { - settings, - mappings, - }, + settings, + mappings, }, { headers: ES_CLIENT_HEADERS, @@ -184,7 +182,7 @@ export function createCreateIndexStream({ ); if (actions.length) { - await client.indices.updateAliases({ body: { actions } }); + await client.indices.updateAliases({ actions }); } stats.createdIndex(index, { settings }); diff --git a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/kibana_index.ts b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/kibana_index.ts index c0f3294a8a976..b43d5594bc3f4 100644 --- a/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/kibana_index.ts +++ b/src/platform/packages/shared/kbn-es-archiver/src/lib/indices/kibana_index.ts @@ -45,7 +45,7 @@ export async function deleteSavedObjectIndices({ await client.indices.putSettings( { index: indexNames, - body: { blocks: { read_only: false } }, + settings: { blocks: { read_only: false } }, }, { headers: ES_CLIENT_HEADERS, @@ -123,13 +123,11 @@ export async function cleanSavedObjectIndices({ { index, refresh: true, - body: { - query: { - bool: { - must_not: { - ids: { - values: ['space:default'], - }, + query: { + bool: { + must_not: { + ids: { + values: ['space:default'], }, }, }, @@ -168,7 +166,7 @@ export async function createDefaultSpace({ index, client }: { index: string; cli index, id: 'space:default', refresh: 'wait_for', - body: { + document: { type: 'space', updated_at: new Date().toISOString(), space: { diff --git a/src/platform/packages/shared/kbn-es-query/src/es_query/decorate_query.ts b/src/platform/packages/shared/kbn-es-query/src/es_query/decorate_query.ts index 3cf8849d97c45..000404525c9fe 100644 --- a/src/platform/packages/shared/kbn-es-query/src/es_query/decorate_query.ts +++ b/src/platform/packages/shared/kbn-es-query/src/es_query/decorate_query.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SerializableRecord } from '@kbn/utility-types'; import { extend, defaults } from 'lodash'; import { getTimeZoneFromSettings } from '../utils'; diff --git a/src/platform/packages/shared/kbn-es-query/src/es_query/from_filters.ts b/src/platform/packages/shared/kbn-es-query/src/es_query/from_filters.ts index 96929fceaecc1..2a796a847e628 100644 --- a/src/platform/packages/shared/kbn-es-query/src/es_query/from_filters.ts +++ b/src/platform/packages/shared/kbn-es-query/src/es_query/from_filters.ts @@ -8,7 +8,7 @@ */ import { isUndefined } from 'lodash'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { migrateFilter } from './migrate_filter'; import { filterMatchesIndex } from './filter_matches_index'; import { Filter, cleanFilter, isFilterDisabled } from '../filters'; diff --git a/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts b/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts index 285fceea2c8b9..3a89f4af0b2de 100644 --- a/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts +++ b/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isString } from 'lodash'; /** diff --git a/src/platform/packages/shared/kbn-es-query/src/es_query/types.ts b/src/platform/packages/shared/kbn-es-query/src/es_query/types.ts index 6c03336c10237..8da90e00ed02d 100644 --- a/src/platform/packages/shared/kbn-es-query/src/es_query/types.ts +++ b/src/platform/packages/shared/kbn-es-query/src/es_query/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; /** * A field's sub type diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/custom_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/custom_filter.ts index 24cae10c8b027..a92d1ac701c74 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/custom_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/custom_filter.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Filter, FilterMeta, FILTERS, FilterStateStore } from './types'; /** @public */ diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/match_all_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/match_all_filter.ts index 0e01d6d17e38d..a7b4758f6d84d 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/match_all_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/match_all_filter.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SerializableRecord } from '@kbn/utility-types'; import { has } from 'lodash'; import type { Filter, FilterMeta } from './types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts index b5a7946b8d299..37a2d134d6094 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts @@ -18,7 +18,7 @@ import { } from './phrase_filter'; import { fields, getField } from '../stubs'; import { DataViewBase } from '../../es_query'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Filter } from './types'; describe('Phrase filter builder', () => { diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts index 4b0aa9632b2ff..f853abdfb508a 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SerializableRecord } from '@kbn/utility-types'; import { get, has, isPlainObject } from 'lodash'; import type { Filter, FilterMeta } from './types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrases_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrases_filter.ts index b9e42d797f284..6e35b80f997eb 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrases_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrases_filter.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Filter, FilterMeta, FILTERS } from './types'; import { getPhraseScript, PhraseFilterValue } from './phrase_filter'; import type { DataViewFieldBase, DataViewBaseNoFields } from '../../es_query'; diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts index 5b89e57548655..307f8f6fba138 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { map, reduce, mapValues, has, get, keys, pickBy } from 'lodash'; import type { SerializableRecord } from '@kbn/utility-types'; import type { Filter, FilterMeta, FilterMetaParams } from './types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts index ed983219b7fd9..abefcc8e219f7 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts @@ -8,7 +8,7 @@ */ import { JsonObject } from '@kbn/utility-types'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { nodeTypes } from '../node_types'; import { KQLSyntaxError } from '../kuery_syntax_error'; import type { KqlContext, KueryNode, KueryParseOptions, KueryQueryOptions } from '../types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.ts index cbe5b6f618640..8b57f777b8334 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import * as ast from '../ast'; import type { DataViewBase, KueryNode, KueryQueryOptions } from '../../..'; import type { KqlFunctionNode } from '../node_types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/exists.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/exists.ts index d4ca260e0a7a2..02a5779432331 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/exists.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/exists.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { DataViewFieldBase, DataViewBase, KueryQueryOptions } from '../../..'; import type { KqlFunctionNode, KqlLiteralNode } from '../node_types'; import type { KqlContext } from '../types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts index 32e758da70d5c..e1a7a7cd8b2e0 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts @@ -12,7 +12,7 @@ import { fields } from '../../filters/stubs'; import * as is from './is'; import { DataViewBase } from '../../..'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { KQL_NODE_TYPE_WILDCARD } from '../node_types/wildcard'; import { KQL_NODE_TYPE_LITERAL } from '../node_types/literal'; import { KqlIsFunctionNode } from './is'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.ts index 8cd6077f9d0a8..f0d2515c12551 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.ts @@ -8,7 +8,7 @@ */ import { isUndefined } from 'lodash'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { getPhraseScript } from '../../filters'; import { getFields } from './utils/get_fields'; import { getTimeZoneFromSettings, getDataViewFieldSubtypeNested } from '../../utils'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.ts index afb1312e97213..09620be7e93af 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import * as ast from '../ast'; import * as literal from '../node_types/literal'; import type { DataViewBase, KueryQueryOptions } from '../../..'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.ts index 592a379fcf001..aa9ac0fa0c3e5 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import * as ast from '../ast'; import type { DataViewBase, KueryNode, KueryQueryOptions } from '../../..'; import type { KqlFunctionNode } from '../node_types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.ts index e9823e607d168..ad0ac49237b16 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import * as ast from '../ast'; import type { DataViewBase, KueryNode, KueryQueryOptions } from '../../..'; import type { KqlFunctionNode } from '../node_types'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts index 35bec3fb85782..3c5da79a3e392 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts @@ -12,7 +12,7 @@ import { fields } from '../../filters/stubs'; import { DataViewBase } from '../../..'; import * as range from './range'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { KQL_NODE_TYPE_LITERAL } from '../node_types/literal'; import { KqlRangeFunctionNode } from './range'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.ts index 373a706f9d406..60ae2de513b30 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { buildNode as buildLiteralNode } from '../node_types/literal'; import { type KqlFunctionNode, type KqlLiteralNode, nodeTypes } from '../node_types'; import * as ast from '../ast'; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts index d5d47050c0387..3fcfb7d94a27e 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { toElasticsearchQuery as astToElasticsearchQuery } from './ast'; /** diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/types.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/types.ts index 531735eff65dd..904b775c7945a 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/types.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SerializableRecord } from '@kbn/utility-types'; import { KQL_NODE_TYPE_FUNCTION } from './node_types/function'; import { KQL_NODE_TYPE_LITERAL } from './node_types/literal'; diff --git a/src/platform/packages/shared/kbn-es-types/src/index.ts b/src/platform/packages/shared/kbn-es-types/src/index.ts index 354a26169c328..bd1919ea7ece9 100644 --- a/src/platform/packages/shared/kbn-es-types/src/index.ts +++ b/src/platform/packages/shared/kbn-es-types/src/index.ts @@ -7,10 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; -// TODO: Remove when all usages have been migrated to non-body -import { SearchRequest as SearchRequestWithBodyKey } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { Field, QueryDslFieldAndFormat } from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { InferSearchResponseOf, AggregateOf as AggregationResultOf, @@ -25,7 +22,7 @@ import { export type ESFilter = estypes.QueryDslQueryContainer; // For now, we also accept with body to unblock the migration to without body. -export type ESSearchRequest = estypes.SearchRequest | SearchRequestWithBodyKey; +export type ESSearchRequest = estypes.SearchRequest; export type AggregationOptionsByType = Required; // Typings for Elasticsearch queries and aggregations. These are intended to be @@ -46,7 +43,7 @@ export type ESSearchResponse< > = InferSearchResponseOf; // `fields` parameter from a search request (estypes.SearchRequest) -export type SearchField = QueryDslFieldAndFormat | Field; +export type SearchField = estypes.QueryDslFieldAndFormat | estypes.Field; export type { InferSearchResponseOf, diff --git a/src/platform/packages/shared/kbn-es-types/src/search.ts b/src/platform/packages/shared/kbn-es-types/src/search.ts index a4f8d5de7af7d..3e6e589b61c7b 100644 --- a/src/platform/packages/shared/kbn-es-types/src/search.ts +++ b/src/platform/packages/shared/kbn-es-types/src/search.ts @@ -8,9 +8,7 @@ */ import type { ValuesType, UnionToIntersection } from 'utility-types'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; -// TODO: Remove when all usages have been migrated to non-body -import { SearchRequest as SearchRequestWithBodyKey } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; interface AggregationsAggregationContainer extends Record { aggs?: any; @@ -85,7 +83,7 @@ export type SearchHit< ? { fields: Partial, unknown[]>>; } - : { fields?: Record }) & + : { fields?: Record }) & (TDocValueFields extends DocValueFields ? { fields: Partial, unknown[]>>; @@ -635,14 +633,10 @@ type WrapAggregationResponse = keyof UnionToIntersection extends never export type InferSearchResponseOf< TDocument = unknown, - TSearchRequest extends - | (estypes.SearchRequest & { body?: never }) // the union is necessary for the check 4 lines below - | SearchRequestWithBodyKey = estypes.SearchRequest, + TSearchRequest extends estypes.SearchRequest = estypes.SearchRequest, TOptions extends { restTotalHitsAsInt?: boolean } = {} > = Omit, 'aggregations' | 'hits'> & - (TSearchRequest['body'] extends TopLevelAggregationRequest - ? WrapAggregationResponse> - : TSearchRequest extends TopLevelAggregationRequest + (TSearchRequest extends TopLevelAggregationRequest ? WrapAggregationResponse> : { aggregations?: InvalidAggregationRequest }) & { hits: Omit['hits'], 'total' | 'hits'> & @@ -656,10 +650,7 @@ export type InferSearchResponseOf< relation: 'eq' | 'gte'; }; }) & { - hits: HitsOf< - TSearchRequest extends SearchRequestWithBodyKey ? TSearchRequest['body'] : TSearchRequest, - TDocument - >; + hits: HitsOf; }; }; diff --git a/src/platform/packages/shared/kbn-es/src/cluster.ts b/src/platform/packages/shared/kbn-es/src/cluster.ts index 1396d1102b2f6..7b474ae59729a 100644 --- a/src/platform/packages/shared/kbn-es/src/cluster.ts +++ b/src/platform/packages/shared/kbn-es/src/cluster.ts @@ -14,7 +14,7 @@ import * as path from 'path'; import execa from 'execa'; import { Readable } from 'stream'; import { combineLatest, fromEvent, first } from 'rxjs'; -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { promisify } from 'util'; import { CA_CERT_PATH, ES_NOPASSWORD_P12_PATH, extract } from '@kbn/dev-utils'; import { ToolingLog } from '@kbn/tooling-log'; @@ -428,6 +428,8 @@ export class Cluster { rejectUnauthorized: true, } : undefined, + Connection: HttpConnection, + requestTimeout: 30_000, }); if (!skipReadyCheck) { diff --git a/src/platform/packages/shared/kbn-es/src/utils/docker.ts b/src/platform/packages/shared/kbn-es/src/utils/docker.ts index fef9cd3d1fd9c..2c24e4b25c5ae 100644 --- a/src/platform/packages/shared/kbn-es/src/utils/docker.ts +++ b/src/platform/packages/shared/kbn-es/src/utils/docker.ts @@ -771,6 +771,7 @@ export async function runServerlessEsNode( function getESClient(clientOptions: ClientOptions): Client { return new Client({ Connection: HttpConnection, + requestTimeout: 30_000, ...clientOptions, }); } diff --git a/src/platform/packages/shared/kbn-es/src/utils/native_realm.js b/src/platform/packages/shared/kbn-es/src/utils/native_realm.js index 4f2acd9a35201..618acbf43d28c 100644 --- a/src/platform/packages/shared/kbn-es/src/utils/native_realm.js +++ b/src/platform/packages/shared/kbn-es/src/utils/native_realm.js @@ -27,9 +27,7 @@ exports.NativeRealm = class NativeRealm { await this._client.security.changePassword({ username, refresh: 'wait_for', - body: { - password, - }, + password, }); } catch (err) { const isAnonymousUserPasswordChangeError = diff --git a/src/platform/packages/shared/kbn-es/src/utils/native_realm.test.js b/src/platform/packages/shared/kbn-es/src/utils/native_realm.test.js index 7f73997368b4e..07a6c3af93de1 100644 --- a/src/platform/packages/shared/kbn-es/src/utils/native_realm.test.js +++ b/src/platform/packages/shared/kbn-es/src/utils/native_realm.test.js @@ -134,45 +134,37 @@ describe('setPasswords', () => { }); expect(mockClient.security.changePassword.mock.calls).toMatchInlineSnapshot(` -Array [ - Array [ - Object { - "body": Object { - "password": "bar", - }, - "refresh": "wait_for", - "username": "kibana_system", - }, - ], - Array [ - Object { - "body": Object { - "password": "changeme", - }, - "refresh": "wait_for", - "username": "logstash_system", - }, - ], - Array [ - Object { - "body": Object { - "password": "changeme", - }, - "refresh": "wait_for", - "username": "elastic", - }, - ], - Array [ - Object { - "body": Object { - "password": "changeme", - }, - "refresh": "wait_for", - "username": "beats_system", - }, - ], -] -`); + Array [ + Array [ + Object { + "password": "bar", + "refresh": "wait_for", + "username": "kibana_system", + }, + ], + Array [ + Object { + "password": "changeme", + "refresh": "wait_for", + "username": "logstash_system", + }, + ], + Array [ + Object { + "password": "changeme", + "refresh": "wait_for", + "username": "elastic", + }, + ], + Array [ + Object { + "password": "changeme", + "refresh": "wait_for", + "username": "beats_system", + }, + ], + ] + `); }); }); @@ -204,7 +196,7 @@ describe('setPassword', () => { it('sets password for provided user', async () => { await nativeRealm.setPassword('kibana_system', 'foo'); expect(mockClient.security.changePassword).toHaveBeenCalledWith({ - body: { password: 'foo' }, + password: 'foo', refresh: 'wait_for', username: 'kibana_system', }); diff --git a/src/platform/packages/shared/kbn-ftr-common-functional-services/services/console.ts b/src/platform/packages/shared/kbn-ftr-common-functional-services/services/console.ts index c434a341dc567..bdb140385efe4 100644 --- a/src/platform/packages/shared/kbn-ftr-common-functional-services/services/console.ts +++ b/src/platform/packages/shared/kbn-ftr-common-functional-services/services/console.ts @@ -15,12 +15,10 @@ export function ConsoleProvider({ getService }: FtrProviderContext) { const createIndex = async (indexName: string) => { await client.indices.create({ index: indexName, - body: { - mappings: { - properties: { - foo: { - type: 'text', - }, + mappings: { + properties: { + foo: { + type: 'text', }, }, }, @@ -37,26 +35,22 @@ export function ConsoleProvider({ getService }: FtrProviderContext) { const createLegacyTemplate = async (templateName: string) => { await client.indices.putTemplate({ name: templateName, - body: { - index_patterns: ['*'], - }, + index_patterns: ['*'], }); }; const createComponentTemplate = async (templateName: string) => { await client.cluster.putComponentTemplate({ name: templateName, - body: { - template: { - mappings: { - properties: { - '@timestamp': { - type: 'date', - format: 'date_optional_time||epoch_millis', - }, - message: { - type: 'wildcard', - }, + template: { + mappings: { + properties: { + '@timestamp': { + type: 'date', + format: 'date_optional_time||epoch_millis', + }, + message: { + type: 'wildcard', }, }, }, @@ -71,12 +65,10 @@ export function ConsoleProvider({ getService }: FtrProviderContext) { ) => { await client.indices.putIndexTemplate({ name: templateName, - body: { - index_patterns: indexPatterns, - data_stream: {}, - composed_of: composedOf, - priority: 500, - }, + index_patterns: indexPatterns, + data_stream: {}, + composed_of: composedOf, + priority: 500, }); }; diff --git a/src/platform/packages/shared/kbn-ftr-common-functional-services/services/saved_object_info/saved_object_info.ts b/src/platform/packages/shared/kbn-ftr-common-functional-services/services/saved_object_info/saved_object_info.ts index 7a2a9982679ac..6ab88b5586c4c 100644 --- a/src/platform/packages/shared/kbn-ftr-common-functional-services/services/saved_object_info/saved_object_info.ts +++ b/src/platform/packages/shared/kbn-ftr-common-functional-services/services/saved_object_info/saved_object_info.ts @@ -38,10 +38,14 @@ export const types = await pipe( TE.tryCatch( async () => { - const body = await new Client({ node, Connection: HttpConnection }).search({ + const body = await new Client({ + node, + Connection: HttpConnection, + requestTimeout: 30_000, + }).search({ index, size: 0, - body: query, + ...query, }); return body; }, diff --git a/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts b/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts index 46e6af5855bb5..6a3f9635162de 100644 --- a/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts +++ b/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts @@ -11,10 +11,10 @@ import type { Script, MappingRuntimeField, MappingRuntimeFields, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { RuntimeFieldSpec, RuntimePrimitiveTypes } from '@kbn/data-views-plugin/common'; import type { BoolQuery } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; type RunTimeMappings = | Record & { type: RuntimePrimitiveTypes }> diff --git a/src/platform/packages/shared/kbn-rule-data-utils/src/alerts_as_data_rbac.ts b/src/platform/packages/shared/kbn-rule-data-utils/src/alerts_as_data_rbac.ts index 32606abe31b7b..8da7b3b649a15 100644 --- a/src/platform/packages/shared/kbn-rule-data-utils/src/alerts_as_data_rbac.ts +++ b/src/platform/packages/shared/kbn-rule-data-utils/src/alerts_as_data_rbac.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EsQueryConfig } from '@kbn/es-query'; /** diff --git a/src/platform/packages/shared/kbn-search-errors/src/create_es_error.ts b/src/platform/packages/shared/kbn-search-errors/src/create_es_error.ts index 363fe8636c131..82a178fa47e29 100644 --- a/src/platform/packages/shared/kbn-search-errors/src/create_es_error.ts +++ b/src/platform/packages/shared/kbn-search-errors/src/create_es_error.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import type { ApplicationStart, CoreStart } from '@kbn/core/public'; import type { AbstractDataView } from '@kbn/data-views-plugin/common'; diff --git a/src/platform/packages/shared/kbn-search-errors/src/painless_error.tsx b/src/platform/packages/shared/kbn-search-errors/src/painless_error.tsx index 12385b0db6484..05445132cbdb9 100644 --- a/src/platform/packages/shared/kbn-search-errors/src/painless_error.tsx +++ b/src/platform/packages/shared/kbn-search-errors/src/painless_error.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { ApplicationStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; import { EuiButtonEmpty, EuiSpacer, EuiText, EuiCodeBlock } from '@elastic/eui'; diff --git a/src/platform/packages/shared/kbn-search-errors/src/tsdb_error.tsx b/src/platform/packages/shared/kbn-search-errors/src/tsdb_error.tsx index 2a6a04d8f6e87..a39d39cfff74e 100644 --- a/src/platform/packages/shared/kbn-search-errors/src/tsdb_error.tsx +++ b/src/platform/packages/shared/kbn-search-errors/src/tsdb_error.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { CoreStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; import { EuiLink } from '@elastic/eui'; diff --git a/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.test.ts b/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.test.ts index c5a1352c3d0f9..2a8c57082a921 100644 --- a/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.test.ts +++ b/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { Start as InspectorStartContract } from '@kbn/inspector-plugin/public'; import type { ESQLSearchResponse } from '@kbn/es-types'; import type { RequestAdapter } from '@kbn/inspector-plugin/common/adapters/request'; diff --git a/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.ts b/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.ts index 58e963c239b12..a8e7dde78391b 100644 --- a/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.ts +++ b/src/platform/packages/shared/kbn-search-response-warnings/src/extract_warnings.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { ESQLSearchResponse } from '@kbn/es-types'; import type { Start as InspectorStartContract, RequestAdapter } from '@kbn/inspector-plugin/public'; import type { SearchResponseWarning } from './types'; diff --git a/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.test.ts b/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.test.ts index 12a6832559139..76025a0e7137d 100644 --- a/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.test.ts +++ b/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { coreMock } from '@kbn/core/public/mocks'; import type { Start as InspectorStart, RequestAdapter } from '@kbn/inspector-plugin/public'; import { handleWarnings } from './handle_warnings'; diff --git a/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.tsx b/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.tsx index 7287c3185cc52..8355607e3f590 100644 --- a/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.tsx +++ b/src/platform/packages/shared/kbn-search-response-warnings/src/handle_warnings.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { EuiButtonEmpty, EuiText } from '@elastic/eui'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { AnalyticsServiceStart, NotificationsStart, diff --git a/src/platform/packages/shared/kbn-search-response-warnings/src/types.ts b/src/platform/packages/shared/kbn-search-response-warnings/src/types.ts index d719d0f008b45..22cfd36cc5973 100644 --- a/src/platform/packages/shared/kbn-search-response-warnings/src/types.ts +++ b/src/platform/packages/shared/kbn-search-response-warnings/src/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; /** * A warning object for a search response with incomplete ES results diff --git a/src/platform/packages/shared/kbn-search-types/src/es_search_types.ts b/src/platform/packages/shared/kbn-search-types/src/es_search_types.ts index 3098805558142..d848d3c75ac8c 100644 --- a/src/platform/packages/shared/kbn-search-types/src/es_search_types.ts +++ b/src/platform/packages/shared/kbn-search-types/src/es_search_types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { IKibanaSearchRequest, IKibanaSearchResponse } from './kibana_search_types'; diff --git a/src/platform/packages/shared/kbn-search-types/src/types.ts b/src/platform/packages/shared/kbn-search-types/src/types.ts index 0f19dff76ccf7..ded783201d7f1 100644 --- a/src/platform/packages/shared/kbn-search-types/src/types.ts +++ b/src/platform/packages/shared/kbn-search-types/src/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { ConnectionRequestParams } from '@elastic/transport'; import type { TransportRequestOptions } from '@elastic/elasticsearch'; import type { KibanaExecutionContext } from '@kbn/core/public'; diff --git a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts index f7fb5ee5620dd..0a359bf5847c5 100644 --- a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts +++ b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts @@ -20,11 +20,9 @@ export const createBootstrapIndex = async ( await esClient.indices.create( { index: `${index}-000001`, - body: { - aliases: { - [index]: { - is_write_index: true, - }, + aliases: { + [index]: { + is_write_index: true, }, }, }, diff --git a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_exists/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_exists/index.ts index 23953e6d06526..55f7ee57bcf2a 100644 --- a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_exists/index.ts +++ b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/get_index_exists/index.ts @@ -19,9 +19,7 @@ export const getIndexExists = async ( index, size: 0, allow_no_indices: true, - body: { - terminate_after: 1, - }, + terminate_after: 1, }, { meta: true } ); diff --git a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_privileges/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_privileges/index.ts index a23ad3d23e1e0..afbe2f53a25bc 100644 --- a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_privileges/index.ts +++ b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/read_privileges/index.ts @@ -16,42 +16,40 @@ export const readPrivileges = async ( return ( await esClient.security.hasPrivileges( { - body: { - cluster: [ - 'all', - 'manage', - 'manage_api_key', - 'manage_transform', - 'manage_index_templates', - 'manage_ml', - 'manage_own_api_key', - 'manage_pipeline', - 'manage_security', - 'monitor', - 'monitor_transform', - 'monitor_ml', - ], - index: [ - { - names: [index], - privileges: [ - 'all', - 'create', - 'create_doc', - 'create_index', - 'delete', - 'delete_index', - 'index', - 'manage', - 'maintenance', - 'monitor', - 'read', - 'view_index_metadata', - 'write', - ], - }, - ], - }, + cluster: [ + 'all', + 'manage', + 'manage_api_key', + 'manage_transform', + 'manage_index_templates', + 'manage_ml', + 'manage_own_api_key', + 'manage_pipeline', + 'manage_security', + 'monitor', + 'monitor_transform', + 'monitor_ml', + ], + index: [ + { + names: [index], + privileges: [ + 'all', + 'create', + 'create_doc', + 'create_index', + 'delete', + 'delete_index', + 'index', + 'manage', + 'maintenance', + 'monitor', + 'read', + 'view_index_metadata', + 'write', + ], + }, + ], }, { meta: true } ) diff --git a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/remove_aliases/index.ts b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/remove_aliases/index.ts index 6668b8d570bc1..88f0893a3d4af 100644 --- a/src/platform/packages/shared/kbn-securitysolution-es-utils/src/remove_aliases/index.ts +++ b/src/platform/packages/shared/kbn-securitysolution-es-utils/src/remove_aliases/index.ts @@ -50,8 +50,6 @@ export const removeAliases = async ( } return esClient.indices.updateAliases({ - body: { - actions: aliasesToRemove, - }, + actions: aliasesToRemove, }); }; diff --git a/src/platform/packages/shared/kbn-storage-adapter/src/index_adapter/index.ts b/src/platform/packages/shared/kbn-storage-adapter/src/index_adapter/index.ts index 28b4d4c76a2ea..d0c3a11ee0bc0 100644 --- a/src/platform/packages/shared/kbn-storage-adapter/src/index_adapter/index.ts +++ b/src/platform/packages/shared/kbn-storage-adapter/src/index_adapter/index.ts @@ -242,7 +242,8 @@ export class StorageIndexAdapter; + })) as ESSearchResponse; const minValue = summaryResult.aggregations!.sample.min_max_summary.min.value; const maxValue = summaryResult.aggregations!.sample.min_max_summary.max.value; @@ -226,8 +224,8 @@ export async function getNumberHistogram( const minMaxResult = (await aggSearchWithBody({ aggs: useTopHits ? searchWithHits : searchWithoutHits, })) as - | ESSearchResponse - | ESSearchResponse; + | ESSearchResponse + | ESSearchResponse; const minValue = minMaxResult.aggregations!.sample.min_value.value; const maxValue = minMaxResult.aggregations!.sample.max_value.value; @@ -284,7 +282,7 @@ export async function getNumberHistogram( }; const histogramResult = (await aggSearchWithBody({ aggs: histogramBody })) as ESSearchResponse< unknown, - { body: { aggs: typeof histogramBody } } + { aggs: typeof histogramBody } >; return { @@ -329,7 +327,7 @@ export async function getStringSamples( }; const topValuesResult = (await aggSearchWithBody({ aggs: topValuesBody })) as ESSearchResponse< unknown, - { body: { aggs: typeof topValuesBody } } + { aggs: typeof topValuesBody } >; const topValues = { @@ -382,7 +380,7 @@ export async function getDateHistogram( }; const results = (await aggSearchWithBody({ aggs: histogramBody })) as ESSearchResponse< unknown, - { body: { aggs: typeof histogramBody } } + { aggs: typeof histogramBody } >; return { diff --git a/src/platform/packages/shared/response-ops/alerts-table/hooks/use_sorting.ts b/src/platform/packages/shared/response-ops/alerts-table/hooks/use_sorting.ts index 0eae65918b362..d420fc6a414d3 100644 --- a/src/platform/packages/shared/response-ops/alerts-table/hooks/use_sorting.ts +++ b/src/platform/packages/shared/response-ops/alerts-table/hooks/use_sorting.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type { SortCombinations } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SortCombinations } from '@elastic/elasticsearch/lib/api/types'; import type { EuiDataGridSorting } from '@elastic/eui'; import { EuiDataGridColumnSortingConfig } from '@elastic/eui/src/components/datagrid/data_grid_types'; import { useCallback, useMemo, useState } from 'react'; diff --git a/src/platform/plugins/private/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts/get_saved_object_counts.ts b/src/platform/plugins/private/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts/get_saved_object_counts.ts index fd6f518f6707f..fe02ddabdde3f 100644 --- a/src/platform/plugins/private/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts/get_saved_object_counts.ts +++ b/src/platform/plugins/private/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts/get_saved_object_counts.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsClientContract } from '@kbn/core/server'; const MISSING_TYPE_KEY = 'missing_so_type'; diff --git a/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/es.test.js b/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/es.test.js index 2ff0059ee3ce7..1e4eb1a59c310 100644 --- a/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/es.test.js +++ b/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/es.test.js @@ -251,19 +251,19 @@ describe('es', () => { expect(request.params.index).toEqual('beer'); }); - test('always sets body.size to 0', () => { + test('always sets size to 0', () => { const request = fn(config, tlConfig, emptyScriptFields); - expect(request.params.body.size).toEqual(0); + expect(request.params.size).toEqual(0); }); test('creates a filters agg that contains each of the queries passed', () => { config.q = ['foo', 'bar']; const request = fn(config, tlConfig, emptyScriptFields); - expect(request.params.body.aggs.q.meta.type).toEqual('split'); + expect(request.params.aggs.q.meta.type).toEqual('split'); - const filters = request.params.body.aggs.q.filters.filters; + const filters = request.params.aggs.q.filters.filters; expect(filters.foo.query_string.query).toEqual('foo'); expect(filters.bar.query_string.query).toEqual('bar'); }); @@ -347,10 +347,10 @@ describe('es', () => { }); }); - test('adds the contents of body.extended.es.filter to a filter clause of the bool', () => { + test('adds the contents of extended.es.filter to a filter clause of the bool', () => { config.kibana = true; const request = fn(config, tlConfig, emptyScriptFields); - const filter = request.params.body.query.bool.filter.bool; + const filter = request.params.query.bool.filter.bool; expect(filter.must.length).toEqual(1); expect(filter.must_not.length).toEqual(2); }); @@ -358,13 +358,13 @@ describe('es', () => { test('does not include filters if config.kibana = false', () => { config.kibana = false; const request = fn(config, tlConfig, emptyScriptFields); - expect(request.params.body.query.bool.filter).toEqual(undefined); + expect(request.params.query.bool.filter).toEqual(undefined); }); test('adds a time filter to the bool querys must clause', () => { let request = fn(config, tlConfig, emptyScriptFields); - expect(request.params.body.query.bool.must.length).toEqual(1); - expect(request.params.body.query.bool.must[0]).toEqual({ + expect(request.params.query.bool.must.length).toEqual(1); + expect(request.params.query.bool.must[0]).toEqual({ range: { '@timestamp': { format: 'strict_date_optional_time', @@ -376,7 +376,7 @@ describe('es', () => { config.kibana = true; request = fn(config, tlConfig, emptyScriptFields); - expect(request.params.body.query.bool.must.length).toEqual(1); + expect(request.params.query.bool.must.length).toEqual(1); }); }); @@ -385,7 +385,7 @@ describe('es', () => { config.split = ['beer:5', 'wine:10', ':lemo:nade::15', ':jui:ce:723::45']; const request = fn(config, tlConfig, {}); - let aggs = request.params.body.aggs.q.aggs; + let aggs = request.params.aggs.q.aggs; expect(aggs.beer.meta.type).toEqual('split'); expect(aggs.beer.terms.field).toEqual('beer'); @@ -426,7 +426,7 @@ describe('es', () => { }; const request = fn(config, tlConfig, scriptFields); - const aggs = request.params.body.aggs.q.aggs; + const aggs = request.params.aggs.q.aggs; expect(aggs.scriptedBeer.meta.type).toEqual('split'); expect(aggs.scriptedBeer.terms.script).toEqual({ diff --git a/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/lib/build_request.js b/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/lib/build_request.js index 570bd05f97f64..df7955267e213 100644 --- a/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/lib/build_request.js +++ b/src/platform/plugins/private/vis_types/timelion/server/series_functions/es/lib/build_request.js @@ -71,14 +71,12 @@ export default function buildRequest(config, tlConfig, scriptFields, runtimeFiel const request = { index: config.index, ...(includeFrozen ? { ignore_throttled: false } : {}), - body: { - query: { - bool: bool, - }, - aggs: aggs, - size: 0, - runtime_mappings: runtimeFields, + query: { + bool: bool, }, + aggs: aggs, + size: 0, + runtime_mappings: runtimeFields, }; if (timeout) { diff --git a/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts b/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts index 3187c131fa00a..3decf9bd3064d 100644 --- a/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts +++ b/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts @@ -10,7 +10,7 @@ import moment from 'moment'; import { i18n } from '@kbn/i18n'; import { cloneDeep, isPlainObject } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Assign } from 'utility-types'; import { dateHistogramInterval } from '@kbn/data-plugin/common'; import { TimeCache } from './time_cache'; @@ -231,7 +231,7 @@ export class EsQueryParser { */ _injectContextVars( obj: Assign< - Query | estypes.SearchRequest['body']['aggs'], + Query | estypes.SearchRequest['aggs'], { interval?: { '%autointerval%': true | number } | string; } diff --git a/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.test.ts b/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.test.ts index c23e3b8139455..c0861abbddaf3 100644 --- a/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.test.ts +++ b/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.test.ts @@ -45,10 +45,8 @@ describe('extendSearchParamsWithRuntimeFields', () => { expect(await extendSearchParamsWithRuntimeFields(dataViewsStart, requestParams, 'index')) .toMatchInlineSnapshot(` Object { - "body": Object { - "runtime_mappings": Object { - "foo": Object {}, - }, + "runtime_mappings": Object { + "foo": Object {}, }, } `); @@ -56,10 +54,8 @@ describe('extendSearchParamsWithRuntimeFields', () => { test('should use runtime mappings from spec if it is specified', async () => { const requestParams = { - body: { - runtime_mappings: { - test: {}, - }, + runtime_mappings: { + test: {}, }, } as unknown as ReturnType; const runtimeFields = { foo: {} }; @@ -69,10 +65,8 @@ describe('extendSearchParamsWithRuntimeFields', () => { expect(await extendSearchParamsWithRuntimeFields(dataViewsStart, requestParams, 'index')) .toMatchInlineSnapshot(` Object { - "body": Object { - "runtime_mappings": Object { - "test": Object {}, - }, + "runtime_mappings": Object { + "test": Object {}, }, } `); diff --git a/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.ts b/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.ts index 0fa1d15371539..4e1888948191a 100644 --- a/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.ts +++ b/src/platform/plugins/private/vis_types/vega/public/data_model/search_api.ts @@ -28,7 +28,7 @@ export const extendSearchParamsWithRuntimeFields = async ( indexPatternString?: string ) => { if (indexPatternString) { - let runtimeMappings = requestParams.body?.runtime_mappings; + let runtimeMappings = requestParams.runtime_mappings; if (!runtimeMappings) { const indexPattern = (await indexPatterns.find(indexPatternString, 1)).find( @@ -39,7 +39,7 @@ export const extendSearchParamsWithRuntimeFields = async ( return { ...requestParams, - body: { ...requestParams.body, runtime_mappings: runtimeMappings }, + runtime_mappings: runtimeMappings, }; } @@ -67,8 +67,9 @@ export class SearchAPI { return combineLatest( searchRequests.map((request) => { - const requestId = request.name; - const requestParams = getSearchParamsFromRequest(request, { + const { name: requestId, ...restRequest } = request; + + const requestParams = getSearchParamsFromRequest(restRequest, { getConfig: this.dependencies.uiSettings.get.bind(this.dependencies.uiSettings), }); @@ -82,7 +83,7 @@ export class SearchAPI { ...request, searchSessionId: this.searchSessionId, }); - requestResponders[requestId].json(params.body); + requestResponders[requestId].json(params); } }), switchMap((params) => diff --git a/src/platform/plugins/private/vis_types/vega/public/data_model/types.ts b/src/platform/plugins/private/vis_types/vega/public/data_model/types.ts index 68750c79a3959..0ad7209661614 100644 --- a/src/platform/plugins/private/vis_types/vega/public/data_model/types.ts +++ b/src/platform/plugins/private/vis_types/vega/public/data_model/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Assign } from '@kbn/utility-types'; import { Spec } from 'vega'; import { EsQueryParser } from './es_query_parser'; diff --git a/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/get_range_slider_control_factory.test.tsx b/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/get_range_slider_control_factory.test.tsx index 026abce4538b7..607eb57b5368d 100644 --- a/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/get_range_slider_control_factory.test.tsx +++ b/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/get_range_slider_control_factory.test.tsx @@ -10,7 +10,7 @@ import React from 'react'; import { of } from 'rxjs'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DataViewField } from '@kbn/data-views-plugin/common'; import { SerializedPanelState } from '@kbn/presentation-publishing'; import { fireEvent, render, waitFor } from '@testing-library/react'; diff --git a/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/has_no_results.ts b/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/has_no_results.ts index fae0f816492f5..3967dce7223ec 100644 --- a/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/has_no_results.ts +++ b/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/has_no_results.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DataView } from '@kbn/data-views-plugin/public'; import { AggregateQuery, Filter, Query, TimeRange } from '@kbn/es-query'; import { PublishesDataViews } from '@kbn/presentation-publishing'; diff --git a/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/min_max.ts b/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/min_max.ts index e38902bee5a4f..bec65c5fa90b5 100644 --- a/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/min_max.ts +++ b/src/platform/plugins/shared/controls/public/controls/data_controls/range_slider/min_max.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DataView, DataViewField } from '@kbn/data-views-plugin/public'; import { AggregateQuery, Filter, Query, TimeRange } from '@kbn/es-query'; import { PublishesDataViews, PublishingSubject } from '@kbn/presentation-publishing'; diff --git a/src/platform/plugins/shared/controls/server/options_list/options_list_suggestions_route.ts b/src/platform/plugins/shared/controls/server/options_list/options_list_suggestions_route.ts index 63176c31b3b7f..86f45103e15d6 100644 --- a/src/platform/plugins/shared/controls/server/options_list/options_list_suggestions_route.ts +++ b/src/platform/plugins/shared/controls/server/options_list/options_list_suggestions_route.ts @@ -145,7 +145,10 @@ export const setupOptionsListSuggestionsRoute = ( /** * Run ES query */ - const rawEsResult = await esClient.search({ index, body }, { signal: abortController.signal }); + const rawEsResult = await esClient.search( + { index, ...body }, + { signal: abortController.signal } + ); /** * Parse ES response into Options List Response diff --git a/src/platform/plugins/shared/dashboard/server/usage/dashboard_telemetry_collection_task.ts b/src/platform/plugins/shared/dashboard/server/usage/dashboard_telemetry_collection_task.ts index 7eb4cebc39e49..3da2a9d731f72 100644 --- a/src/platform/plugins/shared/dashboard/server/usage/dashboard_telemetry_collection_task.ts +++ b/src/platform/plugins/shared/dashboard/server/usage/dashboard_telemetry_collection_task.ts @@ -127,7 +127,7 @@ export function dashboardTaskRunner(logger: Logger, core: CoreSetup, embeddable: index: dashboardIndex, ignore_unavailable: true, filter_path: ['hits.hits', '_scroll_id'], - body: { query: { bool: { filter: { term: { type: 'dashboard' } } } } }, + query: { bool: { filter: { term: { type: 'dashboard' } } } }, scroll: '30s', }; diff --git a/src/platform/plugins/shared/data/common/search/aggs/agg_configs.ts b/src/platform/plugins/shared/data/common/search/aggs/agg_configs.ts index 1d0bc99d5ee6d..770ba5521cb6d 100644 --- a/src/platform/plugins/shared/data/common/search/aggs/agg_configs.ts +++ b/src/platform/plugins/shared/data/common/search/aggs/agg_configs.ts @@ -13,7 +13,7 @@ import { i18n } from '@kbn/i18n'; import type { Assign } from '@kbn/utility-types'; import { isRangeFilter, TimeRange, RangeFilter } from '@kbn/es-query'; import type { DataView } from '@kbn/data-views-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IndexPatternLoadExpressionFunctionDefinition } from '@kbn/data-views-plugin/common'; import { buildExpression, buildExpressionFunction } from '@kbn/expressions-plugin/common'; import { ISearchOptions, IEsSearchResponse } from '@kbn/search-types'; diff --git a/src/platform/plugins/shared/data/common/search/aggs/agg_type.ts b/src/platform/plugins/shared/data/common/search/aggs/agg_type.ts index 661443c1f5664..1e9b7dc43f372 100644 --- a/src/platform/plugins/shared/data/common/search/aggs/agg_type.ts +++ b/src/platform/plugins/shared/data/common/search/aggs/agg_type.ts @@ -14,7 +14,7 @@ import { DatatableColumnType } from '@kbn/expressions-plugin/common'; import type { RequestAdapter } from '@kbn/inspector-plugin/common'; import type { SerializedFieldFormat } from '@kbn/field-formats-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { FieldFormatParams } from '@kbn/field-formats-plugin/common'; import type { ISearchSource } from '../../../public'; import { initParams } from './agg_params'; diff --git a/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts b/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts index 29b62fa29c9e3..0d48a5b37527d 100644 --- a/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts +++ b/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts @@ -19,7 +19,7 @@ import { AggConfigs, CreateAggConfigParams } from '../agg_configs'; import { BUCKET_TYPES } from './bucket_agg_types'; import { IBucketAggConfig } from './bucket_agg_type'; import { mockAggTypesRegistry } from '../test_helpers'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { isSamplingEnabled } from '../utils/sampler'; const indexPattern = { diff --git a/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts b/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts index a7a43686bfba6..e56795ad71786 100644 --- a/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts +++ b/src/platform/plugins/shared/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts @@ -9,7 +9,7 @@ import { isNumber, keys, values, find, each, cloneDeep, flatten } from 'lodash'; import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { buildExistsFilter, buildPhrasesFilter, diff --git a/src/platform/plugins/shared/data/common/search/aggs/metrics/top_metrics.ts b/src/platform/plugins/shared/data/common/search/aggs/metrics/top_metrics.ts index df54a125145de..9619a19d69625 100644 --- a/src/platform/plugins/shared/data/common/search/aggs/metrics/top_metrics.ts +++ b/src/platform/plugins/shared/data/common/search/aggs/metrics/top_metrics.ts @@ -8,7 +8,7 @@ */ import _ from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { aggTopMetricsFnName } from './top_metrics_fn'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; diff --git a/src/platform/plugins/shared/data/common/search/aggs/utils/time_splits.ts b/src/platform/plugins/shared/data/common/search/aggs/utils/time_splits.ts index 690a2258eeca4..9cb0c062e7f41 100644 --- a/src/platform/plugins/shared/data/common/search/aggs/utils/time_splits.ts +++ b/src/platform/plugins/shared/data/common/search/aggs/utils/time_splits.ts @@ -9,7 +9,7 @@ import moment from 'moment-timezone'; import { isArray } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RangeFilter } from '@kbn/es-query'; import { AggGroupNames } from '../agg_groups'; diff --git a/src/platform/plugins/shared/data/common/search/expressions/eql.ts b/src/platform/plugins/shared/data/common/search/expressions/eql.ts index 5e37f4782a4f8..769c02ccee9ab 100644 --- a/src/platform/plugins/shared/data/common/search/expressions/eql.ts +++ b/src/platform/plugins/shared/data/common/search/expressions/eql.ts @@ -11,7 +11,7 @@ import { i18n } from '@kbn/i18n'; import { buildEsQuery } from '@kbn/es-query'; import { ExpressionFunctionDefinition } from '@kbn/expressions-plugin/common'; -import { EqlSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { EqlSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import { lastValueFrom } from 'rxjs'; import { RequestStatistics, RequestAdapter } from '@kbn/inspector-plugin/common'; import type { ISearchGeneric } from '@kbn/search-types'; @@ -102,7 +102,7 @@ export const getEqlFn = ({ query: args.query, size: args.size, fields: args.field, - } as unknown as Required['body']; + } as EqlSearchRequest; if (input) { const dataview = args.index ? await dataViews.create({ title: args.index }) : undefined; @@ -150,8 +150,8 @@ export const getEqlFn = ({ search( { params: { + ...dsl, index: args.index, - body: dsl, }, }, { abortSignal, strategy: EQL_SEARCH_STRATEGY } diff --git a/src/platform/plugins/shared/data/common/search/expressions/es_raw_response.ts b/src/platform/plugins/shared/data/common/search/expressions/es_raw_response.ts index 63b454a83c053..e21f4b5e7ed23 100644 --- a/src/platform/plugins/shared/data/common/search/expressions/es_raw_response.ts +++ b/src/platform/plugins/shared/data/common/search/expressions/es_raw_response.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ExpressionTypeDefinition } from '@kbn/expressions-plugin/common'; const name = 'es_raw_response'; diff --git a/src/platform/plugins/shared/data/common/search/expressions/esdsl.ts b/src/platform/plugins/shared/data/common/search/expressions/esdsl.ts index cd574a2477764..05fe559d970d9 100644 --- a/src/platform/plugins/shared/data/common/search/expressions/esdsl.ts +++ b/src/platform/plugins/shared/data/common/search/expressions/esdsl.ts @@ -136,7 +136,7 @@ export const getEsdslFn = ({ params: { index: args.index, size: args.size, - body: dsl, + ...dsl, }, }, { abortSignal } diff --git a/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.test.ts b/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.test.ts index 68b9d234e6667..3ef7a9a29a11b 100644 --- a/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.test.ts +++ b/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.test.ts @@ -34,19 +34,14 @@ describe('getSearchParams', () => { const searchParams = getSearchParamsFromRequest( { index: 'abc', - body: { - query: 123, - track_total_hits: true, - }, + query: [{ query: '123', language: 'kql' }], + track_total_hits: true, }, { getConfig } ); expect(searchParams.index).toBe('abc'); - // @ts-expect-error `track_total_hits` not allowed at top level for `typesWithBodyKey` expect(searchParams.track_total_hits).toBe(true); - expect(searchParams.body).toStrictEqual({ - query: 123, - }); + expect(searchParams.query).toStrictEqual([{ query: '123', language: 'kql' }]); }); test('sets expand_wildcards=all if data view has allowHidden=true', () => { @@ -62,10 +57,8 @@ describe('getSearchParams', () => { const searchParams = getSearchParamsFromRequest( { index, - body: { - query: 123, - track_total_hits: true, - }, + query: [{ query: '123', language: 'kql' }], + track_total_hits: true, }, { getConfig } ); @@ -85,10 +78,8 @@ describe('getSearchParams', () => { const searchParams = getSearchParamsFromRequest( { index, - body: { - query: 123, - track_total_hits: true, - }, + query: [{ query: '123', language: 'kql' }], + track_total_hits: true, }, { getConfig } ); diff --git a/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.ts b/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.ts index f1784770fe3ba..e4a38bc684307 100644 --- a/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.ts +++ b/src/platform/plugins/shared/data/common/search/search_source/fetch/get_search_params.ts @@ -33,16 +33,13 @@ export function getSearchParamsFromRequest( ): ISearchRequestParams { const { getConfig } = dependencies; const searchParams = { preference: getEsPreference(getConfig) }; - // eslint-disable-next-line @typescript-eslint/naming-convention - const { track_total_hits, ...body } = searchRequest.body; const dataView = typeof searchRequest.index !== 'string' ? searchRequest.index : undefined; const index = dataView?.title ?? `${searchRequest.index}`; + // @ts-expect-error elasticsearch@9.0.0 `query` types don't match (it seems like it's been wrong here for a while) return { + ...searchRequest, index, - body, - // @ts-ignore - track_total_hits, ...(dataView?.getAllowHidden() && { expand_wildcards: 'all' }), ...searchParams, }; diff --git a/src/platform/plugins/shared/data/common/search/search_source/inspect/inspector_stats.ts b/src/platform/plugins/shared/data/common/search/search_source/inspect/inspector_stats.ts index cbddde6836449..c3e57f7f16e5c 100644 --- a/src/platform/plugins/shared/data/common/search/search_source/inspect/inspector_stats.ts +++ b/src/platform/plugins/shared/data/common/search/search_source/inspect/inspector_stats.ts @@ -15,7 +15,7 @@ */ import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RequestStatistics } from '@kbn/inspector-plugin/common'; import type { ISearchSource } from '../../../../public'; diff --git a/src/platform/plugins/shared/data/common/search/search_source/normalize_sort_request.ts b/src/platform/plugins/shared/data/common/search/search_source/normalize_sort_request.ts index fe7ac90862138..9c7a26e7f6dc1 100644 --- a/src/platform/plugins/shared/data/common/search/search_source/normalize_sort_request.ts +++ b/src/platform/plugins/shared/data/common/search/search_source/normalize_sort_request.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { DataView } from '@kbn/data-views-plugin/common'; import { EsQuerySortValue } from './types'; diff --git a/src/platform/plugins/shared/data/common/search/search_source/search_source.ts b/src/platform/plugins/shared/data/common/search/search_source/search_source.ts index 6e47b09509d24..aeb532e11deb0 100644 --- a/src/platform/plugins/shared/data/common/search/search_source/search_source.ts +++ b/src/platform/plugins/shared/data/common/search/search_source/search_source.ts @@ -71,10 +71,11 @@ import { concat, omitBy, isNil, + omit, } from 'lodash'; import { catchError, finalize, first, last, map, shareReplay, switchMap, tap } from 'rxjs'; import { defer, EMPTY, from, lastValueFrom, Observable } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { buildEsQuery, Filter, @@ -795,9 +796,15 @@ export class SearchSource { const metaFields = getConfig(UI_SETTINGS.META_FIELDS) ?? []; const searchRequest = this.mergeProps(); - searchRequest.body = searchRequest.body || {}; - const { body, index } = searchRequest; - const dataView = this.getDataView(index); + const bodyParams = omit(searchRequest, [ + 'index', + 'filters', + 'highlightAll', + 'fieldsFromSource', + 'body', + ]); + const body = { ...bodyParams, ...searchRequest.body }; + const dataView = this.getDataView(searchRequest.index); // get some special field types from the index pattern const { docvalueFields, scriptFields, runtimeFields } = dataView?.getComputedFields() ?? { @@ -809,7 +816,9 @@ export class SearchSource { // set defaults const _source = - index && !Object.hasOwn(body, '_source') ? dataView?.getSourceFiltering() : body._source; + searchRequest.index && !Object.hasOwn(body, '_source') + ? dataView?.getSourceFiltering() + : body._source; // get filter if data view specified, otherwise null filter const filter = this.getFieldFilter({ bodySourceExcludes: _source?.excludes, metaFields }); @@ -855,7 +864,7 @@ export class SearchSource { // 2. Create a data view using the index pattern `kibana*` and don't use a timestamp field. // 3. Uncomment the lines below, navigate to Discover, // and switch to the data view created in step 2. - // body.query.bool.must.push({ + // query.bool.must.push({ // error_query: { // indices: [ // { @@ -879,7 +888,7 @@ export class SearchSource { } const builtQuery = this.getBuiltEsQuery({ - index, + index: searchRequest.index, query: searchRequest.query, filters: searchRequest.filters, getConfig, @@ -887,7 +896,7 @@ export class SearchSource { }); const bodyToReturn = { - ...searchRequest.body, + ...body, pit: searchRequest.pit, query: builtQuery, highlight: @@ -913,9 +922,9 @@ export class SearchSource { }; return omitByIsNil({ - ...searchRequest, + ...omit(searchRequest, ['query', 'filters', 'fieldsFromSource']), body: omitByIsNil(bodyToReturn), - indexType: this.getIndexType(index), + indexType: this.getIndexType(searchRequest.index), highlightAll: searchRequest.highlightAll && builtQuery ? undefined : searchRequest.highlightAll, }); @@ -1092,7 +1101,7 @@ export class SearchSource { filter: originalFilters, aggs: searchSourceAggs, parent, - size: omit, + size: _size, // omit it sort, index, ...searchSourceFields diff --git a/src/platform/plugins/shared/data/common/search/search_source/types.ts b/src/platform/plugins/shared/data/common/search/search_source/types.ts index f6cc13b229b82..ae2db6b2e652a 100644 --- a/src/platform/plugins/shared/data/common/search/search_source/types.ts +++ b/src/platform/plugins/shared/data/common/search/search_source/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RequestAdapter } from '@kbn/inspector-plugin/common'; import type { AggregateQuery, Filter, Query } from '@kbn/es-query'; import type { Serializable, SerializableRecord } from '@kbn/utility-types'; diff --git a/src/platform/plugins/shared/data/common/search/strategies/eql_search/types.ts b/src/platform/plugins/shared/data/common/search/strategies/eql_search/types.ts index 1a608e8f02007..73951c68bbfb6 100644 --- a/src/platform/plugins/shared/data/common/search/strategies/eql_search/types.ts +++ b/src/platform/plugins/shared/data/common/search/strategies/eql_search/types.ts @@ -9,12 +9,11 @@ import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types'; import type { EqlSearchRequest } from '@elastic/elasticsearch/lib/api/types'; -import type { EqlSearchRequest as EqlSearchRequestWithBody } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { TransportRequestOptions } from '@elastic/elasticsearch'; export const EQL_SEARCH_STRATEGY = 'eql'; -export type EqlRequestParams = EqlSearchRequest | EqlSearchRequestWithBody; +export type EqlRequestParams = EqlSearchRequest; export interface EqlSearchStrategyRequest extends IKibanaSearchRequest { /** diff --git a/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.test.ts b/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.test.ts index 8c9fb108f23ef..6d6ff9c931c69 100644 --- a/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.test.ts +++ b/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.test.ts @@ -8,7 +8,7 @@ */ import { getTotalLoaded, shimHitsTotal } from './response_utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; describe('response utils', () => { describe('getTotalLoaded', () => { diff --git a/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.ts b/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.ts index 04d1a5d11cbee..60661f0110be2 100644 --- a/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.ts +++ b/src/platform/plugins/shared/data/common/search/strategies/es_search/response_utils.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ISearchOptions } from '@kbn/search-types'; /** diff --git a/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/eql.test.ts.snap b/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/eql.test.ts.snap index ea1d33aef1b12..5ae5a4e83c3f0 100644 --- a/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/eql.test.ts.snap +++ b/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/eql.test.ts.snap @@ -4,33 +4,31 @@ exports[`eql correctly handles filter, query and timerange on context 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "fields": Array [], - "filter": Object { - "bool": Object { - "filter": Array [ - Object { - "match_phrase": Object { - "gender": "male", - }, + "fields": Array [], + "filter": Object { + "bool": Object { + "filter": Array [ + Object { + "match_phrase": Object { + "gender": "male", }, - ], - "must": Array [ - Object { - "query_string": Object { - "query": "*", - "time_zone": true, - }, + }, + ], + "must": Array [ + Object { + "query_string": Object { + "query": "*", + "time_zone": true, }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, - "query": "test", - "size": 4, }, "index": "kibana_sample_data_logs", + "query": "test", + "size": 4, }, }, "type": "eql_raw_response", @@ -41,26 +39,24 @@ exports[`eql correctly handles input adds filters 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "fields": Array [], - "filter": Object { - "bool": Object { - "filter": Array [ - Object { - "match_phrase": Object { - "gender": "male", - }, + "fields": Array [], + "filter": Object { + "bool": Object { + "filter": Array [ + Object { + "match_phrase": Object { + "gender": "male", }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], }, - "query": "test", - "size": 0, }, "index": "test", + "query": "test", + "size": 0, }, }, "type": "eql_raw_response", @@ -71,26 +67,24 @@ exports[`eql correctly handles input adds filters to query with filters 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "fields": Array [], - "filter": Object { - "bool": Object { - "filter": Array [ - Object { - "match_phrase": Object { - "gender": "male", - }, + "fields": Array [], + "filter": Object { + "bool": Object { + "filter": Array [ + Object { + "match_phrase": Object { + "gender": "male", }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], }, - "query": "test", - "size": 4, }, "index": "kibana_sample_data_logs", + "query": "test", + "size": 4, }, }, "type": "eql_raw_response", @@ -101,27 +95,25 @@ exports[`eql correctly handles input adds query 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "fields": Array [], - "filter": Object { - "bool": Object { - "filter": Array [], - "must": Array [ - Object { - "query_string": Object { - "query": "*", - "time_zone": true, - }, + "fields": Array [], + "filter": Object { + "bool": Object { + "filter": Array [], + "must": Array [ + Object { + "query_string": Object { + "query": "*", + "time_zone": true, }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, - "query": "test", - "size": 0, }, "index": "test", + "query": "test", + "size": 0, }, }, "type": "eql_raw_response", @@ -132,27 +124,25 @@ exports[`eql correctly handles input adds query to a query with filters 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "fields": Array [], - "filter": Object { - "bool": Object { - "filter": Array [], - "must": Array [ - Object { - "query_string": Object { - "query": "*", - "time_zone": true, - }, + "fields": Array [], + "filter": Object { + "bool": Object { + "filter": Array [], + "must": Array [ + Object { + "query_string": Object { + "query": "*", + "time_zone": true, }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, - "query": "test", - "size": 4, }, "index": "kibana_sample_data_logs", + "query": "test", + "size": 4, }, }, "type": "eql_raw_response", @@ -163,20 +153,18 @@ exports[`eql correctly handles input ignores timerange 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "fields": Array [], - "filter": Object { - "bool": Object { - "filter": Array [], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + "fields": Array [], + "filter": Object { + "bool": Object { + "filter": Array [], + "must": Array [], + "must_not": Array [], + "should": Array [], }, - "query": "test", - "size": 0, }, "index": "test", + "query": "test", + "size": 0, }, }, "type": "eql_raw_response", diff --git a/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/esdsl.test.ts.snap b/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/esdsl.test.ts.snap index cd71217276373..820266a0f737c 100644 --- a/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/esdsl.test.ts.snap +++ b/src/platform/plugins/shared/data/public/search/expressions/__snapshots__/esdsl.test.ts.snap @@ -4,36 +4,34 @@ exports[`esdsl correctly handles filter, query and timerange on context 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "_source": false, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "match_phrase": Object { - "gender": "male", - }, + "_source": false, + "index": "kibana_sample_data_logs", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "match_phrase": Object { + "gender": "male", }, - ], - "must": Array [ - Object { - "query_string": Object { - "query": "*", - "time_zone": true, - }, + }, + ], + "must": Array [ + Object { + "query_string": Object { + "query": "*", + "time_zone": true, }, - Object { - "term": Object { - "machine.os.keyword": "osx", - }, + }, + Object { + "term": Object { + "machine.os.keyword": "osx", }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, }, - "index": "kibana_sample_data_logs", "size": 4, }, }, @@ -45,23 +43,21 @@ exports[`esdsl correctly handles input adds filters 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "match_phrase": Object { - "gender": "male", - }, + "index": "test", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "match_phrase": Object { + "gender": "male", }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], }, }, - "index": "test", "size": 0, }, }, @@ -73,30 +69,28 @@ exports[`esdsl correctly handles input adds filters to query with filters 1`] = Object { "body": Object { "params": Object { - "body": Object { - "_source": false, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "match_phrase": Object { - "gender": "male", - }, + "_source": false, + "index": "kibana_sample_data_logs", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "match_phrase": Object { + "gender": "male", }, - ], - "must": Array [ - Object { - "term": Object { - "machine.os.keyword": "osx", - }, + }, + ], + "must": Array [ + Object { + "term": Object { + "machine.os.keyword": "osx", }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, }, - "index": "kibana_sample_data_logs", "size": 4, }, }, @@ -108,24 +102,22 @@ exports[`esdsl correctly handles input adds query 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [], - "must": Array [ - Object { - "query_string": Object { - "query": "*", - "time_zone": true, - }, + "index": "test", + "query": Object { + "bool": Object { + "filter": Array [], + "must": Array [ + Object { + "query_string": Object { + "query": "*", + "time_zone": true, }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, }, - "index": "test", "size": 0, }, }, @@ -137,30 +129,28 @@ exports[`esdsl correctly handles input adds query to a query with filters 1`] = Object { "body": Object { "params": Object { - "body": Object { - "_source": false, - "query": Object { - "bool": Object { - "filter": Array [], - "must": Array [ - Object { - "query_string": Object { - "query": "*", - "time_zone": true, - }, + "_source": false, + "index": "kibana_sample_data_logs", + "query": Object { + "bool": Object { + "filter": Array [], + "must": Array [ + Object { + "query_string": Object { + "query": "*", + "time_zone": true, }, - Object { - "term": Object { - "machine.os.keyword": "osx", - }, + }, + Object { + "term": Object { + "machine.os.keyword": "osx", }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, }, - "index": "kibana_sample_data_logs", "size": 4, }, }, @@ -172,17 +162,15 @@ exports[`esdsl correctly handles input ignores timerange 1`] = ` Object { "body": Object { "params": Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + "index": "test", + "query": Object { + "bool": Object { + "filter": Array [], + "must": Array [], + "must_not": Array [], + "should": Array [], }, }, - "index": "test", "size": 0, }, }, diff --git a/src/platform/plugins/shared/data/public/search/search_interceptor/search_interceptor.ts b/src/platform/plugins/shared/data/public/search/search_interceptor/search_interceptor.ts index 432f9906a51d2..479d4433a3bf3 100644 --- a/src/platform/plugins/shared/data/public/search/search_interceptor/search_interceptor.ts +++ b/src/platform/plugins/shared/data/public/search/search_interceptor/search_interceptor.ts @@ -31,7 +31,12 @@ import { takeUntil, tap, } from 'rxjs'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; +import type { + AsyncSearchGetResponse, + ErrorResponseBase, + SqlGetAsyncResponse, +} from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { PublicMethodsOf } from '@kbn/utility-types'; import type { HttpSetup, IHttpFetchError } from '@kbn/core-http-browser'; @@ -59,11 +64,6 @@ import type { } from '@kbn/search-types'; import { createEsError, isEsError, renderSearchError } from '@kbn/search-errors'; import type { IKibanaSearchResponse, ISearchOptions } from '@kbn/search-types'; -import { - AsyncSearchGetResponse, - ErrorResponseBase, - SqlGetAsyncResponse, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { ENHANCED_ES_SEARCH_STRATEGY, ESQL_ASYNC_SEARCH_STRATEGY, diff --git a/src/platform/plugins/shared/data/public/search/search_service.ts b/src/platform/plugins/shared/data/public/search/search_service.ts index 6d2e09a5ef300..00690e91955e7 100644 --- a/src/platform/plugins/shared/data/public/search/search_service.ts +++ b/src/platform/plugins/shared/data/public/search/search_service.ts @@ -8,7 +8,7 @@ */ import { i18n } from '@kbn/i18n'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { handleWarnings } from '@kbn/search-response-warnings'; import { CoreSetup, diff --git a/src/platform/plugins/shared/data/server/kql_telemetry/usage_collector/fetch.ts b/src/platform/plugins/shared/data/server/kql_telemetry/usage_collector/fetch.ts index 3b1e8e73a0631..a591bb57aaac5 100644 --- a/src/platform/plugins/shared/data/server/kql_telemetry/usage_collector/fetch.ts +++ b/src/platform/plugins/shared/data/server/kql_telemetry/usage_collector/fetch.ts @@ -32,7 +32,7 @@ export function fetchProvider(getIndexForType: (type: string) => Promise esClient.search( { index: await getIndexForType('config'), - body: { query: { term: { type: 'config' } } }, + query: { term: { type: 'config' } }, }, { ignore: [404] } ), diff --git a/src/platform/plugins/shared/data/server/search/collectors/search/fetch.ts b/src/platform/plugins/shared/data/server/search/collectors/search/fetch.ts index 077e5e6defc28..21501f3508f22 100644 --- a/src/platform/plugins/shared/data/server/search/collectors/search/fetch.ts +++ b/src/platform/plugins/shared/data/server/search/collectors/search/fetch.ts @@ -20,9 +20,7 @@ export function fetchProvider(getIndexForType: (type: string) => Promise const esResponse = await esClient.search( { index: searchIndex, - body: { - query: { term: { type: { value: 'search-telemetry' } } }, - }, + query: { term: { type: { value: 'search-telemetry' } } }, }, { ignore: [404] } ); diff --git a/src/platform/plugins/shared/data/server/search/collectors/search_session/fetch.ts b/src/platform/plugins/shared/data/server/search/collectors/search_session/fetch.ts index ca9e76cd2d9b4..61e1b2e210bf4 100644 --- a/src/platform/plugins/shared/data/server/search/collectors/search_session/fetch.ts +++ b/src/platform/plugins/shared/data/server/search/collectors/search_session/fetch.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Logger } from '@kbn/core/server'; import { CollectorFetchContext } from '@kbn/usage-collection-plugin/server'; import { ReportedUsage } from './register'; @@ -24,13 +24,11 @@ export function fetchProvider(getIndexForType: (type: string) => Promise const searchSessionIndex = await getIndexForType(SEARCH_SESSION_TYPE); const esResponse = await esClient.search({ index: searchSessionIndex, - body: { - size: 0, - aggs: { - persisted: { - terms: { - field: `${SEARCH_SESSION_TYPE}.persisted`, - }, + size: 0, + aggs: { + persisted: { + terms: { + field: `${SEARCH_SESSION_TYPE}.persisted`, }, }, }, diff --git a/src/platform/plugins/shared/data/server/search/strategies/common/async_utils.ts b/src/platform/plugins/shared/data/server/search/strategies/common/async_utils.ts index 5f944f52abc14..e54c8fa3f317c 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/common/async_utils.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/common/async_utils.ts @@ -28,7 +28,6 @@ export function getCommonDefaultAsyncSubmitParams( } ): Pick< AsyncSearchSubmitRequest, - // @ts-expect-error 'keep_alive' has been removed from the spec due to a misunderstanding, but it still works 'keep_alive' | 'wait_for_completion_timeout' | 'keep_on_completion' > { const useSearchSessions = diff --git a/src/platform/plugins/shared/data/server/search/strategies/eql_search/eql_search_strategy.test.ts b/src/platform/plugins/shared/data/server/search/strategies/eql_search/eql_search_strategy.test.ts index 204a6bcce558f..7a4a95c3e6de8 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/eql_search/eql_search_strategy.test.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/eql_search/eql_search_strategy.test.ts @@ -82,7 +82,7 @@ describe('EQL search strategy', () => { } as unknown as SearchStrategyDependencies; params = { index: 'logstash-*', - body: { query: 'process where 1 == 1' }, + query: 'process where 1 == 1', }; options = { ignore: [400] }; }); @@ -94,7 +94,7 @@ describe('EQL search strategy', () => { const [[request, requestOptions]] = mockEqlSearch.mock.calls; expect(request).toEqual({ - body: { query: 'process where 1 == 1' }, + query: 'process where 1 == 1', ignore_unavailable: true, index: 'logstash-*', keep_alive: '60000ms', @@ -271,6 +271,7 @@ describe('EQL search strategy', () => { it('passes transport options for search without id', async () => { const eqlSearch = eqlSearchStrategyProvider(mockSearchConfig, mockLogger); + // @ts-expect-error missing required `query` const eql: EqlSearchStrategyRequest = { params: { index: 'all' } }; await firstValueFrom(eqlSearch.search(eql, { transport: { ignore: [400] } }, mockDeps)); const [[_params, requestOptions]] = mockEqlSearch.mock.calls; @@ -282,6 +283,7 @@ describe('EQL search strategy', () => { it('passes along a timestamp_field argument', async () => { const eqlSearch = eqlSearchStrategyProvider(mockSearchConfig, mockLogger); const request: EqlSearchStrategyRequest = { + // @ts-expect-error missing required `query` params: { index: 'all', timestamp_field: 'timestamp' }, }; @@ -294,6 +296,7 @@ describe('EQL search strategy', () => { it('passes along an event_category_field argument', async () => { const eqlSearch = eqlSearchStrategyProvider(mockSearchConfig, mockLogger); const request: EqlSearchStrategyRequest = { + // @ts-expect-error missing required `query` params: { index: 'all', event_category_field: 'event_category' }, }; @@ -308,6 +311,7 @@ describe('EQL search strategy', () => { it('passes along a tiebreaker_field argument', async () => { const eqlSearch = eqlSearchStrategyProvider(mockSearchConfig, mockLogger); const request: EqlSearchStrategyRequest = { + // @ts-expect-error missing required `query` params: { index: 'all', tiebreaker_field: 'event_category' }, }; diff --git a/src/platform/plugins/shared/data/server/search/strategies/eql_search/types.ts b/src/platform/plugins/shared/data/server/search/strategies/eql_search/types.ts index 6645619fe396f..578fbe6d1a764 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/eql_search/types.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/eql_search/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface EqlSearchResponse extends estypes.SearchResponse { id?: string; diff --git a/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.test.ts b/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.test.ts index c771cc08b5a5d..743341a7d60f6 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.test.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { pluginInitializerContextConfigMock } from '@kbn/core/server/mocks'; import { esSearchStrategyProvider, toKibanaSearchResponse } from './es_search_strategy'; diff --git a/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.ts b/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.ts index 39e2b6616239d..cd89370af03c3 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/es_search/es_search_strategy.ts @@ -11,7 +11,7 @@ import { firstValueFrom, from, Observable } from 'rxjs'; import type { ConnectionRequestParams } from '@elastic/transport'; import { tap } from 'rxjs'; import type { Logger, SharedGlobalConfig } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { shimHitsTotal, getTotalLoaded } from '../../../../common'; import { sanitizeRequestParams } from '../../sanitize_request_params'; import { getKbnSearchError, KbnSearchError } from '../../report_search_error'; @@ -56,7 +56,7 @@ export const esSearchStrategyProvider = ( throw new KbnSearchError(`Unsupported index pattern type ${request.indexType}`, 400); } - const isPit = request.params?.body?.pit != null; + const isPit = request.params?.pit != null; const search = async () => { try { diff --git a/src/platform/plugins/shared/data/server/search/strategies/es_search/request_utils.ts b/src/platform/plugins/shared/data/server/search/strategies/es_search/request_utils.ts index 729a04da39b17..8b5824a1b39bc 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/es_search/request_utils.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/es_search/request_utils.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { IUiSettingsClient, SharedGlobalConfig } from '@kbn/core/server'; import { UI_SETTINGS } from '../../../../common'; diff --git a/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.test.ts b/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.test.ts index a778ebbc89675..f476dd904e57d 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.test.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.test.ts @@ -71,6 +71,7 @@ const mockRollupResponse = { describe('ES search strategy', () => { const mockApiCaller = jest.fn(); + const mockRollupSearchCaller = jest.fn(); const mockStatusCaller = jest.fn(); const mockGetCaller = jest.fn(); const mockSubmitCaller = jest.fn(); @@ -92,6 +93,9 @@ describe('ES search strategy', () => { delete: mockDeleteCaller, }, transport: { request: mockApiCaller }, + rollup: { + rollupSearch: mockRollupSearchCaller, + }, }, }, searchSessionsClient: createSearchSessionsClientMock(), @@ -132,7 +136,7 @@ describe('ES search strategy', () => { it('makes a POST request with params when no ID provided', async () => { mockSubmitCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -144,14 +148,14 @@ describe('ES search strategy', () => { expect(mockSubmitCaller).toBeCalled(); const request = mockSubmitCaller.mock.calls[0][0]; expect(request.index).toEqual(params.index); - expect(request.body).toEqual(params.body); + expect(request.query).toEqual(params.query); expect(request).toHaveProperty('keep_alive', '60000ms'); }); it('returns status if incomplete', async () => { mockStatusCaller.mockResolvedValueOnce(mockAsyncStatusResponse(false)); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -170,7 +174,7 @@ describe('ES search strategy', () => { mockStatusCaller.mockResolvedValueOnce(mockAsyncStatusResponse(true)); mockGetCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -192,7 +196,7 @@ describe('ES search strategy', () => { const params = { index: 'logstash-*', - body: { query: {} }, + query: {}, wait_for_completion_timeout: '10s', keep_alive: '5m', }; @@ -214,7 +218,7 @@ describe('ES search strategy', () => { it('sets transport options on POST requests', async () => { const transportOptions = { maxRetries: 1 }; mockSubmitCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -229,7 +233,7 @@ describe('ES search strategy', () => { 1, expect.objectContaining({ batched_reduce_size: 64, - body: { query: {} }, + query: {}, ignore_unavailable: true, index: 'logstash-*', keep_alive: '60000ms', @@ -245,7 +249,7 @@ describe('ES search strategy', () => { it('sets transport options on GET requests', async () => { mockStatusCaller.mockResolvedValueOnce(mockAsyncStatusResponse(true)); mockGetCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -270,7 +274,7 @@ describe('ES search strategy', () => { it('sets wait_for_completion_timeout and keep_alive in the request', async () => { mockSubmitCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'foo-*', body: {} }; + const params = { index: 'foo-*' }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -286,9 +290,9 @@ describe('ES search strategy', () => { }); it('calls the rollup API if the index is a rollup type', async () => { - mockApiCaller.mockResolvedValueOnce(mockRollupResponse); + mockRollupSearchCaller.mockResolvedValueOnce(mockRollupResponse); - const params = { index: 'foo-程', body: {} }; + const params = { index: 'foo-程' }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -306,17 +310,24 @@ describe('ES search strategy', () => { ) .toPromise(); - expect(mockApiCaller).toBeCalled(); - const { method, path } = mockApiCaller.mock.calls[0][0]; - expect(method).toBe('POST'); - expect(path).toBe('/foo-%E7%A8%8B/_rollup_search'); + expect(mockRollupSearchCaller).toBeCalled(); + expect(mockRollupSearchCaller).toHaveBeenCalledWith( + { + index: 'foo-程', + ignore_unavailable: true, + max_concurrent_shard_requests: undefined, + timeout: '100ms', + track_total_hits: true, + }, + { meta: true, signal: undefined } + ); }); it("doesn't call the rollup API if the index is a rollup type BUT rollups are disabled", async () => { mockApiCaller.mockResolvedValueOnce(mockRollupResponse); mockSubmitCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'foo-程', body: { query: {} } }; + const params = { index: 'foo-程', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -350,7 +361,7 @@ describe('ES search strategy', () => { }, }); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -395,7 +406,7 @@ describe('ES search strategy', () => { }); mockDeleteCaller.mockRejectedValueOnce(errResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -423,7 +434,7 @@ describe('ES search strategy', () => { it('Submit search with session id that is not saved creates a search with short keep_alive', async () => { mockSubmitCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -435,7 +446,7 @@ describe('ES search strategy', () => { expect(mockSubmitCaller).toBeCalled(); const request = mockSubmitCaller.mock.calls[0][0]; expect(request.index).toEqual(params.index); - expect(request.body).toEqual(params.body); + expect(request.query).toEqual(params.query); expect(request).toHaveProperty('keep_alive', '60000ms'); }); @@ -443,7 +454,7 @@ describe('ES search strategy', () => { it('Submit search with session id and session is saved creates a search with long keep_alive', async () => { mockSubmitCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -455,7 +466,7 @@ describe('ES search strategy', () => { expect(mockSubmitCaller).toBeCalled(); const request = mockSubmitCaller.mock.calls[0][0]; expect(request.index).toEqual(params.index); - expect(request.body).toEqual(params.body); + expect(request.query).toEqual(params.query); expect(request).toHaveProperty('keep_alive', '604800000ms'); }); @@ -464,7 +475,7 @@ describe('ES search strategy', () => { mockStatusCaller.mockResolvedValueOnce(mockAsyncStatusResponse(true)); mockGetCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -484,7 +495,7 @@ describe('ES search strategy', () => { mockStatusCaller.mockResolvedValueOnce(mockAsyncStatusResponse(true)); mockGetCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -506,7 +517,7 @@ describe('ES search strategy', () => { mockStatusCaller.mockResolvedValueOnce(mockAsyncStatusResponse(true)); mockGetCaller.mockResolvedValueOnce(mockAsyncResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -541,7 +552,7 @@ describe('ES search strategy', () => { }, }); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -582,7 +593,7 @@ describe('ES search strategy', () => { mockSubmitCaller.mockRejectedValue(errResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, @@ -607,7 +618,7 @@ describe('ES search strategy', () => { mockSubmitCaller.mockRejectedValue(errResponse); - const params = { index: 'logstash-*', body: { query: {} } }; + const params = { index: 'logstash-*', query: {} }; const esSearch = await enhancedEsSearchStrategyProvider( mockLegacyConfig$, mockSearchConfig, diff --git a/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.ts b/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.ts index 0099fc31ebec7..c68eb73dd09ca 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.ts @@ -10,12 +10,12 @@ import type { Observable } from 'rxjs'; import type { Logger, SharedGlobalConfig } from '@kbn/core/server'; import { catchError, tap } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { firstValueFrom, from } from 'rxjs'; import type { ISearchOptions, IEsSearchRequest, IEsSearchResponse } from '@kbn/search-types'; import { getKbnServerError } from '@kbn/kibana-utils-plugin/server'; +import { omit } from 'lodash'; import { IAsyncSearchRequestParams } from '../..'; -import { getKbnSearchError } from '../../report_search_error'; +import { getKbnSearchError, KbnSearchError } from '../../report_search_error'; import type { ISearchStrategy, SearchStrategyDependencies } from '../../types'; import type { IAsyncSearchOptions } from '../../../../common'; import { DataViewType, isRunningResponse, pollSearch } from '../../../../common'; @@ -156,23 +156,23 @@ export const enhancedEsSearchStrategyProvider = ( ): Promise { const client = useInternalUser ? esClient.asInternalUser : esClient.asCurrentUser; const legacyConfig = await firstValueFrom(legacyConfig$); - const { body, index, ...params } = request.params!; - const method = 'POST'; - const path = encodeURI(`/${index}/_rollup_search`); const querystring = { ...getShardTimeout(legacyConfig), ...(await getIgnoreThrottled(uiSettingsClient)), ...(await getDefaultSearchParams(uiSettingsClient)), - ...params, }; + // Custom 400 error here because the client tries to run `index.toString()` and we no-longer can rely on ES 400 + if (!request.params?.index) { + throw new KbnSearchError(`"params.index" is required when performing a rollup search`, 400); + } + try { - const esResponse = await client.transport.request( + const esResponse = await client.rollup.rollupSearch( { - method, - path, - body, - querystring, + ...querystring, + ...omit(request.params, ['indexType']), + index: request.params.index, }, { signal: options?.abortSignal, @@ -180,7 +180,7 @@ export const enhancedEsSearchStrategyProvider = ( } ); - const response = esResponse.body as estypes.SearchResponse; + const response = esResponse.body; return { rawResponse: shimHitsTotal(response, options), ...(esResponse.meta?.request?.params diff --git a/src/platform/plugins/shared/data/server/search/strategies/ese_search/request_utils.ts b/src/platform/plugins/shared/data/server/search/strategies/ese_search/request_utils.ts index c1dbfcb8263b7..3169b64114c6a 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/ese_search/request_utils.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/ese_search/request_utils.ts @@ -8,7 +8,7 @@ */ import { IUiSettingsClient } from '@kbn/core/server'; -import { AsyncSearchGetRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AsyncSearchGetRequest } from '@elastic/elasticsearch/lib/api/types'; import { AsyncSearchSubmitRequest } from '@elastic/elasticsearch/lib/api/types'; import { ISearchOptions } from '@kbn/search-types'; import { UI_SETTINGS } from '../../../../common'; @@ -39,7 +39,6 @@ export async function getDefaultAsyncSubmitParams( ): Promise< Pick< AsyncSearchSubmitRequest, - // @ts-expect-error 'keep_alive' has been removed from the spec due to a misunderstanding, but it still works | 'batched_reduce_size' | 'ccs_minimize_roundtrips' | 'keep_alive' diff --git a/src/platform/plugins/shared/data/server/search/strategies/esql_async_search/esql_async_search_strategy.ts b/src/platform/plugins/shared/data/server/search/strategies/esql_async_search/esql_async_search_strategy.ts index f8c686d8e4b9a..aa19caf115496 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/esql_async_search/esql_async_search_strategy.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/esql_async_search/esql_async_search_strategy.ts @@ -11,7 +11,7 @@ import type { IScopedClusterClient, Logger } from '@kbn/core/server'; import { catchError, tap } from 'rxjs'; import { getKbnServerError } from '@kbn/kibana-utils-plugin/server'; import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types'; -import { SqlQueryRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SqlQueryRequest } from '@elastic/elasticsearch/lib/api/types'; import { SqlGetAsyncResponse } from '@elastic/elasticsearch/lib/api/types'; import type { ESQLSearchParams } from '@kbn/es-types'; import { toAsyncKibanaSearchResponse } from './response_utils'; @@ -29,7 +29,7 @@ import { SearchConfigSchema } from '../../../config'; // now we get `all_columns` and `columns` // `columns` contain only columns with data // `all_columns` contain everything -type ESQLQueryRequest = ESQLSearchParams & SqlQueryRequest['body']; +type ESQLQueryRequest = ESQLSearchParams & SqlQueryRequest; export const esqlAsyncSearchStrategyProvider = ( searchConfig: SearchConfigSchema, diff --git a/src/platform/plugins/shared/data/server/search/strategies/sql_search/response_utils.ts b/src/platform/plugins/shared/data/server/search/strategies/sql_search/response_utils.ts index 92fb125dbaa66..e2cca05c9fbd3 100644 --- a/src/platform/plugins/shared/data/server/search/strategies/sql_search/response_utils.ts +++ b/src/platform/plugins/shared/data/server/search/strategies/sql_search/response_utils.ts @@ -8,7 +8,7 @@ */ import type { ConnectionRequestParams } from '@elastic/transport'; -import { SqlQueryResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SqlQueryResponse } from '@elastic/elasticsearch/lib/api/types'; import { SqlSearchStrategyResponse } from '../../../../common'; import { sanitizeRequestParams } from '../../sanitize_request_params'; diff --git a/src/platform/plugins/shared/data_view_field_editor/__jest__/client_integration/field_editor_flyout_preview.test.ts b/src/platform/plugins/shared/data_view_field_editor/__jest__/client_integration/field_editor_flyout_preview.test.ts index 2a05b0d05aa38..e44f3e5cf6960 100644 --- a/src/platform/plugins/shared/data_view_field_editor/__jest__/client_integration/field_editor_flyout_preview.test.ts +++ b/src/platform/plugins/shared/data_view_field_editor/__jest__/client_integration/field_editor_flyout_preview.test.ts @@ -754,10 +754,8 @@ describe('Field editor Preview panel', () => { const expectedParamsToFetchClusterData = { params: { index: indexPatternNameForTest, - body: { - fields: ['*'], - size: 50, - }, + fields: ['*'], + size: 50, }, }; @@ -782,15 +780,13 @@ describe('Field editor Preview panel', () => { expect(searchMeta.totalCalls).toBe(initialCount + 1); expect(searchMeta.lastCallParams).toEqual({ params: { - body: { - fields: ['*'], - query: { - ids: { - values: [nextId], - }, + fields: ['*'], + query: { + ids: { + values: [nextId], }, - size: 1, }, + size: 1, index: indexPatternNameForTest, }, }); diff --git a/src/platform/plugins/shared/data_view_field_editor/public/components/preview/preview_controller.tsx b/src/platform/plugins/shared/data_view_field_editor/public/components/preview/preview_controller.tsx index eb48dc2f7a50e..bcb5a9bd78448 100644 --- a/src/platform/plugins/shared/data_view_field_editor/public/components/preview/preview_controller.tsx +++ b/src/platform/plugins/shared/data_view_field_editor/public/components/preview/preview_controller.tsx @@ -524,10 +524,8 @@ export class PreviewController { .search({ params: { index: this.dataView.getIndexPattern(), - body: { - fields: ['*'], - size: limit, - }, + fields: ['*'], + size: limit, }, }) .toPromise() @@ -571,13 +569,11 @@ export class PreviewController { .search({ params: { index: this.dataView.getIndexPattern(), - body: { - size: 1, - fields: ['*'], - query: { - ids: { - values: [id], - }, + size: 1, + fields: ['*'], + query: { + ids: { + values: [id], }, }, }, diff --git a/src/platform/plugins/shared/data_view_management/public/components/edit_index_pattern/scripted_fields_table/types.ts b/src/platform/plugins/shared/data_view_management/public/components/edit_index_pattern/scripted_fields_table/types.ts index a85ee3267759c..7fad4140bcbec 100644 --- a/src/platform/plugins/shared/data_view_management/public/components/edit_index_pattern/scripted_fields_table/types.ts +++ b/src/platform/plugins/shared/data_view_management/public/components/edit_index_pattern/scripted_fields_table/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; /** @internal **/ export interface ScriptedFieldItem { name: string; diff --git a/src/platform/plugins/shared/data_view_management/public/components/field_editor/field_editor.tsx b/src/platform/plugins/shared/data_view_management/public/components/field_editor/field_editor.tsx index 25a1609266fef..88bf41077d2cb 100644 --- a/src/platform/plugins/shared/data_view_management/public/components/field_editor/field_editor.tsx +++ b/src/platform/plugins/shared/data_view_management/public/components/field_editor/field_editor.tsx @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import React, { PureComponent, Fragment } from 'react'; import { intersection, union, get } from 'lodash'; diff --git a/src/platform/plugins/shared/data_view_management/public/components/field_editor/types.ts b/src/platform/plugins/shared/data_view_management/public/components/field_editor/types.ts index 6e55eb687d67c..7c2ac7fcc85a3 100644 --- a/src/platform/plugins/shared/data_view_management/public/components/field_editor/types.ts +++ b/src/platform/plugins/shared/data_view_management/public/components/field_editor/types.ts @@ -10,7 +10,7 @@ import { ReactText } from 'react'; import { Query } from '@kbn/es-query'; import { HttpStart } from '@kbn/core/public'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; export type SampleInput = ReactText | ReactText[] | Record; export interface Sample { diff --git a/src/platform/plugins/shared/data_view_management/public/scripting_languages/index.ts b/src/platform/plugins/shared/data_view_management/public/scripting_languages/index.ts index 4d8a3e5f076f2..152a8106298e2 100644 --- a/src/platform/plugins/shared/data_view_management/public/scripting_languages/index.ts +++ b/src/platform/plugins/shared/data_view_management/public/scripting_languages/index.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { HttpStart, NotificationsStart } from '@kbn/core/public'; import { SCRIPT_LANGUAGES_ROUTE_LATEST_VERSION } from '@kbn/data-plugin/common'; diff --git a/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.test.ts b/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.test.ts index 3a80d95b0076f..75c4aed2668f2 100644 --- a/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.test.ts +++ b/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.test.ts @@ -47,23 +47,21 @@ describe('preview_scripted_field route', () => { expect(mockClient.search.mock.calls[0][0]).toMatchInlineSnapshot(` Object { - "body": Object { - "_source": undefined, - "query": Object { - "match_all": Object {}, - }, - "script_fields": Object { - "my_scripted_field": Object { - "script": Object { - "lang": "painless", - "source": "doc['foo'].value", - }, + "_source": undefined, + "index": "kibana_sample_data_logs", + "query": Object { + "match_all": Object {}, + }, + "script_fields": Object { + "my_scripted_field": Object { + "script": Object { + "lang": "painless", + "source": "doc['foo'].value", }, }, - "size": 10, - "timeout": "30s", }, - "index": "kibana_sample_data_logs", + "size": 10, + "timeout": "30s", } `); @@ -103,29 +101,27 @@ describe('preview_scripted_field route', () => { expect(mockClient.search.mock.calls[0][0]).toMatchInlineSnapshot(` Object { - "body": Object { - "_source": Array [ - "a", - "b", - "c", - ], - "query": Object { - "bool": Object { - "some": "query", - }, + "_source": Array [ + "a", + "b", + "c", + ], + "index": "kibana_sample_data_logs", + "query": Object { + "bool": Object { + "some": "query", }, - "script_fields": Object { - "my_scripted_field": Object { - "script": Object { - "lang": "painless", - "source": "doc['foo'].value", - }, + }, + "script_fields": Object { + "my_scripted_field": Object { + "script": Object { + "lang": "painless", + "source": "doc['foo'].value", }, }, - "size": 10, - "timeout": "30s", }, - "index": "kibana_sample_data_logs", + "size": 10, + "timeout": "30s", } `); }); diff --git a/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.ts b/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.ts index f5384bedce956..0d7c7b94b6eca 100644 --- a/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.ts +++ b/src/platform/plugins/shared/data_view_management/server/routes/preview_scripted_field.ts @@ -38,18 +38,15 @@ export function registerPreviewScriptedFieldRoute(router: IRouter): void { const response = await client.search( { index, - body: { - _source: - additionalFields && additionalFields.length > 0 ? additionalFields : undefined, - size: 10, - timeout: '30s', - query: query ?? { match_all: {} }, - script_fields: { - [name]: { - script: { - lang: 'painless', - source: script, - }, + _source: additionalFields && additionalFields.length > 0 ? additionalFields : undefined, + size: 10, + timeout: '30s', + query: query ?? { match_all: {} }, + script_fields: { + [name]: { + script: { + lang: 'painless', + source: script, }, }, }, diff --git a/src/platform/plugins/shared/data_views/common/data_views/data_view.ts b/src/platform/plugins/shared/data_views/common/data_views/data_view.ts index 36a4b98eeef24..5bb5cab83abb3 100644 --- a/src/platform/plugins/shared/data_views/common/data_views/data_view.ts +++ b/src/platform/plugins/shared/data_views/common/data_views/data_view.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FieldFormatsStartCommon } from '@kbn/field-formats-plugin/common'; import { castEsToKbnFieldTypeName } from '@kbn/field-types'; import { CharacterNotAllowedInField } from '@kbn/kibana-utils-plugin/common'; diff --git a/src/platform/plugins/shared/data_views/common/data_views/data_view_lazy.ts b/src/platform/plugins/shared/data_views/common/data_views/data_view_lazy.ts index 7b16af56c0601..bea9b49d7a21a 100644 --- a/src/platform/plugins/shared/data_views/common/data_views/data_view_lazy.ts +++ b/src/platform/plugins/shared/data_views/common/data_views/data_view_lazy.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { FieldFormatsStartCommon } from '@kbn/field-formats-plugin/common'; import { castEsToKbnFieldTypeName } from '@kbn/field-types'; diff --git a/src/platform/plugins/shared/data_views/common/types.ts b/src/platform/plugins/shared/data_views/common/types.ts index f1cfa4741ccd2..3c09e2517aa50 100644 --- a/src/platform/plugins/shared/data_views/common/types.ts +++ b/src/platform/plugins/shared/data_views/common/types.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { SavedObject } from '@kbn/core/server'; import type { ErrorToastOptions, ToastInputFields } from '@kbn/core-notifications-browser'; diff --git a/src/platform/plugins/shared/data_views/public/services/has_data.ts b/src/platform/plugins/shared/data_views/public/services/has_data.ts index bcf80ca337460..01f8c294c1dd0 100644 --- a/src/platform/plugins/shared/data_views/public/services/has_data.ts +++ b/src/platform/plugins/shared/data_views/public/services/has_data.ts @@ -155,14 +155,12 @@ export class HasData { ignore_unavailable: true, expand_wildcards: showAllIndices ? 'all' : 'open', index: pattern, - body: { - size: 0, // no hits - aggs: { - indices: { - terms: { - field: '_index', - size: 200, - }, + size: 0, // no hits + aggs: { + indices: { + terms: { + field: '_index', + size: 200, }, }, }, diff --git a/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.test.ts b/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.test.ts index 8990dbc567c77..43606c969e5ab 100644 --- a/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.test.ts +++ b/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { IndexPatternsFetcher } from '.'; import { elasticsearchServiceMock, uiSettingsServiceMock } from '@kbn/core/server/mocks'; import { SavedObjectsClientContract } from '@kbn/core/server'; diff --git a/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.ts b/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.ts index 2bfd0bc2b3c47..aa8ac9f3e11e9 100644 --- a/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.ts +++ b/src/platform/plugins/shared/data_views/server/fetcher/index_patterns_fetcher.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient, IUiSettingsClient } from '@kbn/core/server'; import { keyBy } from 'lodash'; import { defer, from } from 'rxjs'; diff --git a/src/platform/plugins/shared/data_views/server/fetcher/lib/es_api.ts b/src/platform/plugins/shared/data_views/server/fetcher/lib/es_api.ts index 129255a08d4e0..091089b82dd0c 100644 --- a/src/platform/plugins/shared/data_views/server/fetcher/lib/es_api.ts +++ b/src/platform/plugins/shared/data_views/server/fetcher/lib/es_api.ts @@ -8,10 +8,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import type { - ExpandWildcard, - MappingRuntimeFields, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { ExpandWildcard, MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import { QueryDslQueryContainer } from '../../../common/types'; import { convertEsError } from './errors'; diff --git a/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_capabilities.ts b/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_capabilities.ts index 227c3a3e62887..6b6b209c571f4 100644 --- a/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_capabilities.ts +++ b/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_capabilities.ts @@ -9,10 +9,7 @@ import { defaults, keyBy, sortBy } from 'lodash'; -import type { - ExpandWildcard, - MappingRuntimeFields, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { ExpandWildcard, MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, IUiSettingsClient } from '@kbn/core/server'; import { callFieldCapsApi } from '../es_api'; import { readFieldCapsResponse } from './field_caps_response'; diff --git a/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts b/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts index 362470a9eef1e..633a40ff4e803 100644 --- a/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts +++ b/src/platform/plugins/shared/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts @@ -8,7 +8,7 @@ */ import { uniq } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { castEsToKbnFieldTypeName } from '@kbn/field-types'; import { shouldReadFieldFromDocValues } from './should_read_field_from_doc_values'; import { FieldDescriptor } from '../..'; diff --git a/src/platform/plugins/shared/data_views/server/rest_api_routes/internal/fields_for.ts b/src/platform/plugins/shared/data_views/server/rest_api_routes/internal/fields_for.ts index e9aa3dd538818..62aa55e434071 100644 --- a/src/platform/plugins/shared/data_views/server/rest_api_routes/internal/fields_for.ts +++ b/src/platform/plugins/shared/data_views/server/rest_api_routes/internal/fields_for.ts @@ -8,7 +8,7 @@ */ import type { Observable } from 'rxjs'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import type { IRouter, RequestHandler, RouteAuthz, StartServicesAccessor } from '@kbn/core/server'; import { VersionedRouteValidation } from '@kbn/core-http-server'; diff --git a/src/platform/plugins/shared/data_views/server/rest_api_routes/route_types.ts b/src/platform/plugins/shared/data_views/server/rest_api_routes/route_types.ts index f4e9875f4c42e..6c2d0285efc46 100644 --- a/src/platform/plugins/shared/data_views/server/rest_api_routes/route_types.ts +++ b/src/platform/plugins/shared/data_views/server/rest_api_routes/route_types.ts @@ -11,7 +11,7 @@ import { SerializableRecord } from '@kbn/utility-types'; import { IFieldSubType } from '@kbn/es-query'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { RuntimePrimitiveTypes, RuntimeType } from '../../common/types'; // types for REST responses. separate but similar to other types to draw attention to REST api return changes diff --git a/src/platform/plugins/shared/discover/public/application/context/services/_stubs.ts b/src/platform/plugins/shared/discover/public/application/context/services/_stubs.ts index 1569a6f131fb0..90ce84458034a 100644 --- a/src/platform/plugins/shared/discover/public/application/context/services/_stubs.ts +++ b/src/platform/plugins/shared/discover/public/application/context/services/_stubs.ts @@ -10,7 +10,7 @@ import sinon from 'sinon'; import moment from 'moment'; import { of } from 'rxjs'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IKibanaSearchResponse } from '@kbn/search-types'; import type { EsHitRecord } from '@kbn/discover-utils/types'; diff --git a/src/platform/plugins/shared/discover/public/application/context/utils/fetch_hits_in_interval.ts b/src/platform/plugins/shared/discover/public/application/context/utils/fetch_hits_in_interval.ts index 464efc62ac47e..c98979436a885 100644 --- a/src/platform/plugins/shared/discover/public/application/context/utils/fetch_hits_in_interval.ts +++ b/src/platform/plugins/shared/discover/public/application/context/utils/fetch_hits_in_interval.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { lastValueFrom } from 'rxjs'; import { ISearchSource, EsQuerySortValue, SortDirection } from '@kbn/data-plugin/public'; import { buildDataTableRecordList } from '@kbn/discover-utils'; diff --git a/src/platform/plugins/shared/discover/public/application/context/utils/get_es_query_search_after.ts b/src/platform/plugins/shared/discover/public/application/context/utils/get_es_query_search_after.ts index f533f052eea65..e05fe6bf3645a 100644 --- a/src/platform/plugins/shared/discover/public/application/context/utils/get_es_query_search_after.ts +++ b/src/platform/plugins/shared/discover/public/application/context/utils/get_es_query_search_after.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { DataTableRecord } from '@kbn/discover-utils/types'; import { SurrDocType } from '../services/context'; diff --git a/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results.test.tsx b/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results.test.tsx index 9b002178ba0b4..df2f7ae6a5fcf 100644 --- a/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results.test.tsx +++ b/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results.test.tsx @@ -314,17 +314,15 @@ describe('DiscoverNoResults', () => { expect(services.data.search.search).toHaveBeenLastCalledWith( expect.objectContaining({ params: expect.objectContaining({ - body: expect.objectContaining({ - aggs: expect.objectContaining({ - earliest_timestamp: expect.objectContaining({ - min: expect.objectContaining({ - format: 'strict_date_optional_time', - }), + aggs: expect.objectContaining({ + earliest_timestamp: expect.objectContaining({ + min: expect.objectContaining({ + format: 'strict_date_optional_time', }), - latest_timestamp: expect.objectContaining({ - max: expect.objectContaining({ - format: 'strict_date_optional_time', - }), + }), + latest_timestamp: expect.objectContaining({ + max: expect.objectContaining({ + format: 'strict_date_optional_time', }), }), }), diff --git a/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results_suggestions/use_fetch_occurances_range.ts b/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results_suggestions/use_fetch_occurances_range.ts index 386c0d5b4a802..beb8e49877739 100644 --- a/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results_suggestions/use_fetch_occurances_range.ts +++ b/src/platform/plugins/shared/discover/public/application/main/components/no_results/no_results_suggestions/use_fetch_occurances_range.ts @@ -13,7 +13,7 @@ import type { DataView } from '@kbn/data-plugin/common'; import type { AggregateQuery, Filter, Query } from '@kbn/es-query'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { IUiSettingsClient } from '@kbn/core-ui-settings-browser'; -import type { AggregationsSingleMetricAggregateBase } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsSingleMetricAggregateBase } from '@elastic/elasticsearch/lib/api/types'; import { buildEsQuery } from '@kbn/es-query'; import { getEsQueryConfig } from '@kbn/data-plugin/common'; @@ -124,21 +124,19 @@ async function fetchDocumentsTimeRange({ index: dataView.getIndexPattern(), size: 0, track_total_hits: false, - body: { - timeout: '20s', - query: dslQuery ?? { match_all: {} }, - aggs: { - earliest_timestamp: { - min: { - field: dataView.timeFieldName, - format: 'strict_date_optional_time', - }, + timeout: '20s', + query: dslQuery ?? { match_all: {} }, + aggs: { + earliest_timestamp: { + min: { + field: dataView.timeFieldName, + format: 'strict_date_optional_time', }, - latest_timestamp: { - max: { - field: dataView.timeFieldName, - format: 'strict_date_optional_time', - }, + }, + latest_timestamp: { + max: { + field: dataView.timeFieldName, + format: 'strict_date_optional_time', }, }, }, diff --git a/src/platform/plugins/shared/esql/server/services/integration_tests/testbed.ts b/src/platform/plugins/shared/esql/server/services/integration_tests/testbed.ts index 95de7fdf562c3..1109026909d81 100644 --- a/src/platform/plugins/shared/esql/server/services/integration_tests/testbed.ts +++ b/src/platform/plugins/shared/esql/server/services/integration_tests/testbed.ts @@ -48,14 +48,12 @@ export class EsqlServiceTestbed { await client.indices.create({ index: 'lookup_index1', - body: { - settings: { - 'index.mode': 'lookup', - }, - mappings: { - properties: { - field1: { type: 'keyword' }, - }, + settings: { + 'index.mode': 'lookup', + }, + mappings: { + properties: { + field1: { type: 'keyword' }, }, }, }); @@ -63,18 +61,16 @@ export class EsqlServiceTestbed { // Lookup index with aliases await client.indices.create({ index: 'lookup_index2', - body: { - settings: { - 'index.mode': 'lookup', - }, - aliases: { - lookup_index2_alias1: {}, - lookup_index2_alias2: {}, - }, - mappings: { - properties: { - field2: { type: 'keyword' }, - }, + settings: { + 'index.mode': 'lookup', + }, + aliases: { + lookup_index2_alias1: {}, + lookup_index2_alias2: {}, + }, + mappings: { + properties: { + field2: { type: 'keyword' }, }, }, }); diff --git a/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.test.ts b/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.test.ts index 4e6c9542d9e3d..00ad9df997035 100644 --- a/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.test.ts +++ b/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.test.ts @@ -14,7 +14,7 @@ import { encode, decode } from '@kbn/cbor'; import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { ContentStream, ContentStreamEncoding, ContentStreamParameters } from './content_stream'; import type { GetResponse } from '@elastic/elasticsearch/lib/api/types'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { FileDocument } from '../../../../file_client/file_metadata_client/adapters/es_index'; import { IndexRequest } from '@elastic/elasticsearch/lib/api/types'; @@ -85,15 +85,13 @@ describe('ContentStream', () => { const data = await new Promise((resolve) => stream.once('data', resolve)); expect(client.search).toHaveBeenCalledWith({ - body: { - _source: false, - query: { - term: { - _id: 'something.0', - }, + _source: false, + query: { + term: { + _id: 'something.0', }, - size: 1, }, + size: 1, index: 'somewhere', }); expect(data).toEqual(Buffer.from('some content')); diff --git a/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.ts b/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.ts index 2cda6188fc8b3..583c474194b6d 100644 --- a/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.ts +++ b/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/content_stream/content_stream.ts @@ -92,15 +92,13 @@ export class ContentStream extends Duplex { private async getChunkRealIndex(id: string): Promise { const chunkDocMeta = await this.client.search({ index: this.index, - body: { - size: 1, - query: { - term: { - _id: id, - }, + size: 1, + query: { + term: { + _id: id, }, - _source: false, // suppress the document content }, + _source: false, // suppress the document content }); const docIndex = chunkDocMeta.hits.hits?.[0]?._index; diff --git a/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/es.ts b/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/es.ts index 3969ad42e8434..d29bbea0c5f96 100644 --- a/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/es.ts +++ b/src/platform/plugins/shared/files/server/blob_storage_service/adapters/es/es.ts @@ -112,13 +112,11 @@ export class ElasticsearchBlobStorageClient implements BlobStorageClient { await esClient.indices.create({ index, wait_for_active_shards: 'all', - body: { - settings: { - number_of_shards: 1, - auto_expand_replicas: '0-1', - }, - mappings, + settings: { + number_of_shards: 1, + auto_expand_replicas: '0-1', }, + mappings, }); } catch (e) { if (e instanceof errors.ResponseError && e.statusCode === 400) { diff --git a/src/platform/plugins/shared/files/server/file_client/create_es_file_client.test.ts b/src/platform/plugins/shared/files/server/file_client/create_es_file_client.test.ts index 98f22801b0991..f3eb7263d77e4 100644 --- a/src/platform/plugins/shared/files/server/file_client/create_es_file_client.test.ts +++ b/src/platform/plugins/shared/files/server/file_client/create_es_file_client.test.ts @@ -16,7 +16,7 @@ import { MockedLogger } from '@kbn/logging-mocks'; import { createEsFileClient } from './create_es_file_client'; import { FileClient } from './types'; import { ElasticsearchBlobStorageClient } from '../blob_storage_service'; -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { FileDocument } from './file_metadata_client/adapters/es_index'; describe('When initializing file client via createESFileClient()', () => { @@ -81,14 +81,12 @@ describe('When initializing file client via createESFileClient()', () => { it('should use es.search() to retrieve file metadata', async () => { await fileClient.get({ id: '123' }); expect(esClient.search).toHaveBeenCalledWith({ - body: { - query: { - term: { - _id: '123', - }, + query: { + term: { + _id: '123', }, - size: 1, }, + size: 1, index: 'file-meta', }); }); diff --git a/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.test.ts b/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.test.ts index 3f0e0b4146216..fd8d52051392a 100644 --- a/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.test.ts +++ b/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.test.ts @@ -12,7 +12,7 @@ import { Logger } from '@kbn/logging'; import { loggingSystemMock } from '@kbn/core-logging-server-mocks'; import { EsIndexFilesMetadataClient } from '../..'; import { FileMetadata } from '@kbn/shared-ux-file-types'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; describe('EsIndexFilesMetadataClient', () => { let esClient: ReturnType; @@ -65,15 +65,13 @@ describe('EsIndexFilesMetadataClient', () => { await metaClient.update({ id: '123', metadata: generateMetadata() }); expect(esClient.search).toHaveBeenCalledWith({ - body: { - _source: false, - query: { - term: { - _id: '123', - }, + _source: false, + query: { + term: { + _id: '123', }, - size: 1, }, + size: 1, index: 'foo', }); expect(esClient.update).toHaveBeenCalledWith(expect.objectContaining({ index: 'foo-00001' })); diff --git a/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.ts b/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.ts index 6d1a6e5785bf5..ba8de2381cf04 100644 --- a/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.ts +++ b/src/platform/plugins/shared/files/server/file_client/file_metadata_client/adapters/es_index.ts @@ -97,15 +97,13 @@ export class EsIndexFilesMetadataClient implements FileMetadataClie const doc = await this.esClient .search({ index: this.index, - body: { - size: 1, - query: { - term: { - _id: id, - }, + size: 1, + query: { + term: { + _id: id, }, - _source: false, // suppress the document content }, + _source: false, // suppress the document content }) .catch( wrapErrorAndReThrow.withMessagePrefix('EsIndexFilesMetadataClient.getBackingIndex(): ') @@ -156,12 +154,10 @@ export class EsIndexFilesMetadataClient implements FileMetadataClie await esClient .search>({ index, - body: { - size: 1, - query: { - term: { - _id: id, - }, + size: 1, + query: { + term: { + _id: id, }, }, }) diff --git a/src/platform/plugins/shared/home/server/routes/fetch_es_hits_status.ts b/src/platform/plugins/shared/home/server/routes/fetch_es_hits_status.ts index aa4c1286ce67e..0f8fcc36a66ef 100644 --- a/src/platform/plugins/shared/home/server/routes/fetch_es_hits_status.ts +++ b/src/platform/plugins/shared/home/server/routes/fetch_es_hits_status.ts @@ -35,9 +35,7 @@ export const registerHitsStatusRoute = (router: IRouter) => { const body = await client.asCurrentUser.search({ index, size: 1, - body: { - query, - }, + query, }); const count = body.hits.hits.length; diff --git a/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.test.ts b/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.test.ts index 3c13bd4b17b91..fb80d2b87d0dc 100644 --- a/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.test.ts +++ b/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.test.ts @@ -159,16 +159,14 @@ describe('SampleDataInstaller', () => { expect(esClient.asCurrentUser.indices.create).toHaveBeenCalledTimes(1); expect(esClient.asCurrentUser.indices.create).toHaveBeenCalledWith({ index: 'kibana_sample_data_test_single_data_index', - body: { - mappings: { - properties: { - someField: { type: 'keyword' }, - }, - }, - settings: { - index: {}, + mappings: { + properties: { + someField: { type: 'keyword' }, }, }, + settings: { + index: {}, + }, }); }); diff --git a/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.ts b/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.ts index 8bca3142749ea..bf30242a33961 100644 --- a/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.ts +++ b/src/platform/plugins/shared/home/server/services/sample_data/sample_data_installer.ts @@ -161,13 +161,11 @@ export class SampleDataInstaller { if (dataIndex.isDataStream) { const request = { name: index, - body: { - template: { - mappings: { properties: dataIndex.fields }, - }, - index_patterns: [index], - data_stream: {}, + template: { + mappings: { properties: dataIndex.fields }, }, + index_patterns: [index], + data_stream: {}, }; await this.esClient.asCurrentUser.indices.putIndexTemplate(request); @@ -177,14 +175,12 @@ export class SampleDataInstaller { } else { await this.esClient.asCurrentUser.indices.create({ index, - body: { - settings: { - index: { - ...dataIndex.indexSettings, - }, + settings: { + index: { + ...dataIndex.indexSettings, }, - mappings: { properties: dataIndex.fields }, }, + mappings: { properties: dataIndex.fields }, }); } } catch (err) { diff --git a/src/platform/plugins/shared/home/server/services/sample_data/usage/collector_fetch.ts b/src/platform/plugins/shared/home/server/services/sample_data/usage/collector_fetch.ts index 09f9456aa650e..d51f76abb4274 100644 --- a/src/platform/plugins/shared/home/server/services/sample_data/usage/collector_fetch.ts +++ b/src/platform/plugins/shared/home/server/services/sample_data/usage/collector_fetch.ts @@ -40,10 +40,8 @@ export function fetchProvider(getIndexForType: (type: string) => Promise const response = await esClient.search( { index, - body: { - query: { term: { type: { value: 'sample-data-telemetry' } } }, - _source: { includes: ['sample-data-telemetry', 'type', 'updated_at'] }, - }, + query: { term: { type: { value: 'sample-data-telemetry' } } }, + _source: { includes: ['sample-data-telemetry', 'type', 'updated_at'] }, filter_path: 'hits.hits._id,hits.hits._source', }, { diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_health/clusters_health.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_health/clusters_health.tsx index 8ae68594a3869..e7d2a8daeb088 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_health/clusters_health.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_health/clusters_health.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { css } from '@emotion/react'; import { i18n } from '@kbn/i18n'; import { EuiFlexGroup, EuiFlexItem, EuiText, useEuiTheme } from '@elastic/eui'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.test.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.test.tsx index 936e169418b58..c48d38985cc9c 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.test.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.test.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { shallow } from 'enzyme'; import { ClusterView } from './cluster_view'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.tsx index c82097b12c547..5043009e9dec5 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/cluster_view.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { EuiCallOut, EuiText } from '@elastic/eui'; import { ShardsView } from './shards_view'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.test.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.test.tsx index a530b9fec9ff5..ba4079822e42e 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.test.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.test.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { render, screen, fireEvent } from '@testing-library/react'; import { ClustersTable } from './clusters_table'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.tsx index 7da4f0980cea2..cb8c5b2e213a8 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/clusters_table.tsx @@ -8,7 +8,7 @@ */ import React, { useMemo, useState, ReactNode } from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { Comparators, diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/open_shard_failure_flyout_button.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/open_shard_failure_flyout_button.tsx index 736d29a3666b3..53cf50bd74b08 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/open_shard_failure_flyout_button.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/open_shard_failure_flyout_button.tsx @@ -8,7 +8,7 @@ */ import React, { useState } from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { EuiButtonEmpty } from '@elastic/eui'; import { ShardFailureFlyout } from './shard_failure_flyout'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_details.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_details.tsx index 7a2857856b853..226f3be7107a0 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_details.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_details.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { EuiDescriptionList, EuiCodeBlock, EuiText } from '@elastic/eui'; import { getFlattenedObject } from '@kbn/std'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_flyout.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_flyout.tsx index e5e62e135f362..238644e465014 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_flyout.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_flyout.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { EuiButtonIcon, diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_table.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_table.tsx index d47a42c9dcb35..d6ef90b706009 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_table.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shard_failure_table.tsx @@ -8,7 +8,7 @@ */ import React, { useState, ReactNode } from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { EuiBasicTable, type EuiBasicTableColumn, EuiButtonIcon, EuiText } from '@elastic/eui'; import { ShardFailureDetails } from './shard_failure_details'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.test.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.test.tsx index 77d336febfaa9..df0401108d04d 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.test.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.test.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { shallow } from 'enzyme'; import { ShardsView } from './shards_view'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.tsx index 34828f01c4eb7..5819239ea8941 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_table/shards_view/shards_view.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui'; import { OpenShardFailureFlyoutButton } from './open_shard_failure_flyout_button'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_view.tsx b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_view.tsx index fc3ec5796906b..4e1e6be7ec6af 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_view.tsx +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/clusters_view.tsx @@ -8,7 +8,7 @@ */ import React, { Component } from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiSearchBar, type EuiSearchBarOnChangeArgs, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { Request } from '../../../../../../common/adapters/request/types'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/find_clusters.ts b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/find_clusters.ts index 9968cbe39e13a..f706fba4c9a37 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/find_clusters.ts +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/find_clusters.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiSearchBar, type Query } from '@elastic/eui'; import { Request } from '../../../../../../common/adapters/request/types'; import { getLocalClusterDetails, LOCAL_CLUSTER_KEY } from './local_cluster'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_cluster.ts b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_cluster.ts index 13f8dafb1e68b..d5bf77eb942fc 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_cluster.ts +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_cluster.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; export const LOCAL_CLUSTER_KEY = '(local)'; diff --git a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_clusters.test.ts b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_clusters.test.ts index 80111911233e8..1372aa5538500 100644 --- a/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_clusters.test.ts +++ b/src/platform/plugins/shared/inspector/public/views/requests/components/details/clusters_view/local_clusters.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { getLocalClusterDetails } from './local_cluster'; describe('getLocalClusterDetails', () => { diff --git a/src/platform/plugins/shared/saved_objects_management/server/lib/get_saved_objects_counts.ts b/src/platform/plugins/shared/saved_objects_management/server/lib/get_saved_objects_counts.ts index 6a2a56cb398a7..2d967387d4763 100644 --- a/src/platform/plugins/shared/saved_objects_management/server/lib/get_saved_objects_counts.ts +++ b/src/platform/plugins/shared/saved_objects_management/server/lib/get_saved_objects_counts.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsFindOptions } from '@kbn/core-saved-objects-api-server'; import type { SavedObjectsClientContract } from '@kbn/core/server'; diff --git a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.test.ts b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.test.ts index 17a984841bb38..989a7b32ffcad 100644 --- a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.test.ts +++ b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.test.ts @@ -8,7 +8,7 @@ */ import { merge, omit } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { getLocalStats, handleLocalStats } from './get_local_stats'; import { diff --git a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.ts b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.ts index df3fc3d154ede..1a6081fc1716e 100644 --- a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.ts +++ b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_local_stats.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { StatsGetter, StatsCollectionContext, diff --git a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_nodes_usage.ts b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_nodes_usage.ts index aaa27dd1ee98a..ead9c74a8f95b 100644 --- a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_nodes_usage.ts +++ b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_nodes_usage.ts @@ -8,7 +8,7 @@ */ import type { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { TIMEOUT } from './constants'; /** diff --git a/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.test.tsx b/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.test.tsx index d65c5bf1e1cec..f270811a6bdec 100644 --- a/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.test.tsx +++ b/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.test.tsx @@ -36,39 +36,37 @@ describe('Test of helper / hook', () => { const actual = buildSearchBody('1', index, dataView); expect(actual).toMatchInlineSnapshot(` Object { - "body": Object { - "_source": true, - "fields": Array [ - Object { - "field": "*", - "include_unmapped": true, - }, - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "ids": Object { - "values": Array [ - "1", - ], - }, + "_source": true, + "fields": Array [ + Object { + "field": "*", + "include_unmapped": true, + }, + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "ids": Object { + "values": Array [ + "1", + ], }, - Object { - "term": Object { - "_index": "test-index", - }, + }, + Object { + "term": Object { + "_index": "test-index", }, - ], - }, + }, + ], }, - "runtime_mappings": Object {}, - "script_fields": Array [], - "stored_fields": Array [ - "*", - ], - "version": true, }, + "runtime_mappings": Object {}, + "script_fields": Array [], + "stored_fields": Array [ + "*", + ], + "version": true, } `); }); @@ -91,46 +89,44 @@ describe('Test of helper / hook', () => { const actual = buildSearchBody('1', index, dataView); expect(actual).toMatchInlineSnapshot(` Object { - "body": Object { - "_source": true, - "fields": Array [ - Object { - "field": "*", - "include_unmapped": true, - }, - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "ids": Object { - "values": Array [ - "1", - ], - }, + "_source": true, + "fields": Array [ + Object { + "field": "*", + "include_unmapped": true, + }, + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "ids": Object { + "values": Array [ + "1", + ], }, - Object { - "term": Object { - "_index": "test-index", - }, + }, + Object { + "term": Object { + "_index": "test-index", }, - ], - }, - }, - "runtime_mappings": Object { - "myRuntimeField": Object { - "script": Object { - "source": "emit(10.0)", }, - "type": "double", + ], + }, + }, + "runtime_mappings": Object { + "myRuntimeField": Object { + "script": Object { + "source": "emit(10.0)", }, + "type": "double", }, - "script_fields": Array [], - "stored_fields": Array [ - "*", - ], - "version": true, }, + "script_fields": Array [], + "stored_fields": Array [ + "*", + ], + "version": true, } `); }); diff --git a/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.ts b/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.ts index 5b35f0e59e51b..036448181f6d6 100644 --- a/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.ts +++ b/src/platform/plugins/shared/unified_doc_viewer/public/hooks/use_es_doc_search.ts @@ -8,7 +8,7 @@ */ import { useCallback, useEffect, useState } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { lastValueFrom } from 'rxjs'; import type { DataView } from '@kbn/data-views-plugin/public'; import { reportPerformanceMetricEvent } from '@kbn/ebt-tools'; @@ -17,7 +17,7 @@ import { buildDataTableRecord } from '@kbn/discover-utils'; import { ElasticRequestState } from '@kbn/unified-doc-viewer'; import { getUnifiedDocViewerServices } from '../plugin'; -type RequestBody = Pick; +type RequestBody = estypes.SearchRequest; export interface EsDocSearchProps { /** @@ -76,7 +76,7 @@ export function useEsDocSearch({ data.search.search({ params: { index: dataView.getIndexPattern(), - body: buildSearchBody(id, index, dataView)?.body, + ...buildSearchBody(id, index, dataView), }, }) ); @@ -133,19 +133,17 @@ export function buildSearchBody(id: string, index: string, dataView: DataView): const computedFields = dataView.getComputedFields(); const runtimeFields = computedFields.runtimeFields as estypes.MappingRuntimeFields; const request: RequestBody = { - body: { - query: { - bool: { - filter: [{ ids: { values: [id] } }, { term: { _index: index } }], - }, + query: { + bool: { + filter: [{ ids: { values: [id] } }, { term: { _index: index } }], }, - stored_fields: ['*'], - script_fields: computedFields.scriptFields, - version: true, - _source: true, - runtime_mappings: runtimeFields ? runtimeFields : {}, - fields: [{ field: '*', include_unmapped: true }, ...(computedFields.docvalueFields || [])], }, + stored_fields: ['*'], + script_fields: computedFields.scriptFields, + version: true, + _source: true, + runtime_mappings: runtimeFields ? runtimeFields : {}, + fields: [{ field: '*', include_unmapped: true }, ...(computedFields.docvalueFields || [])], }; return request; } diff --git a/src/platform/plugins/shared/unified_histogram/public/chart/chart.tsx b/src/platform/plugins/shared/unified_histogram/public/chart/chart.tsx index 69ace6e73470e..47834d1d41f67 100644 --- a/src/platform/plugins/shared/unified_histogram/public/chart/chart.tsx +++ b/src/platform/plugins/shared/unified_histogram/public/chart/chart.tsx @@ -28,7 +28,7 @@ import type { TimeRange } from '@kbn/es-query'; import { PublishingSubject } from '@kbn/presentation-publishing'; import { RequestStatus } from '@kbn/inspector-plugin/public'; import { IKibanaSearchResponse } from '@kbn/search-types'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { Histogram } from './histogram'; import { UnifiedHistogramSuggestionContext, diff --git a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.test.ts b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.test.ts index daec1b0eb3c49..b9e9d5fb8a841 100644 --- a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.test.ts +++ b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.test.ts @@ -13,7 +13,7 @@ import { ConfigSchema } from '../config'; import type { DeeplyMockedKeys } from '@kbn/utility-types-jest'; import type { DataViewField, FieldSpec } from '@kbn/data-views-plugin/common'; import { termsAggSuggestions } from './terms_agg'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { duration } from 'moment'; let savedObjectsClientMock: jest.Mocked; @@ -61,27 +61,25 @@ describe('terms agg suggestions', () => { expect(args).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "suggestions": Object { - "terms": Object { - "execution_hint": "map", - "field": "field_name", - "include": "query.*", - "shard_size": 10, - }, + "aggs": Object { + "suggestions": Object { + "terms": Object { + "execution_hint": "map", + "field": "field_name", + "include": "query.*", + "shard_size": 10, }, }, - "query": Object { - "bool": Object { - "filter": Array [], - }, - }, - "size": 0, - "terminate_after": 98430, - "timeout": "4513ms", }, "index": "index", + "query": Object { + "bool": Object { + "filter": Array [], + }, + }, + "size": 0, + "terminate_after": 98430, + "timeout": "4513ms", } `); expect(result).toMatchInlineSnapshot(` @@ -107,27 +105,25 @@ describe('terms agg suggestions', () => { expect(args).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "suggestions": Object { - "terms": Object { - "execution_hint": "map", - "field": "fieldName", - "include": "query.*", - "shard_size": 10, - }, + "aggs": Object { + "suggestions": Object { + "terms": Object { + "execution_hint": "map", + "field": "fieldName", + "include": "query.*", + "shard_size": 10, }, }, - "query": Object { - "bool": Object { - "filter": Array [], - }, - }, - "size": 0, - "terminate_after": 98430, - "timeout": "4513ms", }, "index": "index", + "query": Object { + "bool": Object { + "filter": Array [], + }, + }, + "size": 0, + "terminate_after": 98430, + "timeout": "4513ms", } `); expect(result).toMatchInlineSnapshot(` diff --git a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.ts b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.ts index a8e37796789bb..cb9da0b71bdd1 100644 --- a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.ts +++ b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_agg.ts @@ -9,7 +9,7 @@ import { get, map } from 'lodash'; import { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { getFieldSubtypeNested } from '@kbn/data-plugin/common'; import type { FieldSpec } from '@kbn/data-views-plugin/common'; import { ConfigSchema } from '../config'; @@ -45,7 +45,7 @@ export async function termsAggSuggestions( const body = await getBody(autocompleteSearchOptions, field ?? fieldName, query, filters); const result = await esClient.search( - { index, body }, + { index, ...body }, { signal: abortSignal, } diff --git a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.test.ts b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.test.ts index 6010212188695..0d6ec5728fc70 100644 --- a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.test.ts +++ b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.test.ts @@ -12,7 +12,7 @@ import { coreMock } from '@kbn/core/server/mocks'; import { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; import { ConfigSchema } from '../config'; import type { DeeplyMockedKeys } from '@kbn/utility-types-jest'; -import { TermsEnumResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { TermsEnumResponse } from '@elastic/elasticsearch/lib/api/types'; import type { DataViewField } from '@kbn/data-views-plugin/common'; let savedObjectsClientMock: jest.Mocked; @@ -54,24 +54,22 @@ describe('_terms_enum suggestions', () => { expect(args).toMatchInlineSnapshot(` Object { - "body": Object { - "field": "field_name", - "index_filter": Object { - "bool": Object { - "must": Array [], - "must_not": Object { - "terms": Object { - "_tier": Array [ - "data_cold", - "data_frozen", - ], - }, + "field": "field_name", + "index": "index", + "index_filter": Object { + "bool": Object { + "must": Array [], + "must_not": Object { + "terms": Object { + "_tier": Array [ + "data_cold", + "data_frozen", + ], }, }, }, - "string": "query", }, - "index": "index", + "string": "query", } `); expect(result).toEqual(mockResponse.terms); @@ -92,24 +90,22 @@ describe('_terms_enum suggestions', () => { expect(args).toMatchInlineSnapshot(` Object { - "body": Object { - "field": "fieldName", - "index_filter": Object { - "bool": Object { - "must": Array [], - "must_not": Object { - "terms": Object { - "_tier": Array [ - "data_cold", - "data_frozen", - ], - }, + "field": "fieldName", + "index": "index", + "index_filter": Object { + "bool": Object { + "must": Array [], + "must_not": Object { + "terms": Object { + "_tier": Array [ + "data_cold", + "data_frozen", + ], }, }, }, - "string": "query", }, - "index": "index", + "string": "query", } `); expect(result).toEqual(mockResponse.terms); diff --git a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.ts b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.ts index 462d7b283eabd..d396a28d0740b 100644 --- a/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.ts +++ b/src/platform/plugins/shared/unified_search/server/autocomplete/terms_enum.ts @@ -8,7 +8,7 @@ */ import { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FieldSpec } from '@kbn/data-views-plugin/common'; import { findIndexPatternById, getFieldByName } from '../data_views'; import { ConfigSchema } from '../config'; @@ -54,6 +54,6 @@ export async function termsEnumSuggestions( }, }; - const { terms } = await esClient.termsEnum({ index, body }, { signal: abortSignal }); + const { terms } = await esClient.termsEnum({ index, ...body }, { signal: abortSignal }); return terms; } diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts b/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts index d22372e920234..d062b0018e9f4 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts @@ -88,7 +88,6 @@ describe('AbstractSearchStrategy', () => { expect((await requestContext.search).search).toHaveBeenCalledWith( { params: { - body: {}, index: 'index', }, indexType: undefined, diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts b/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts index 7765be0d1f040..8deefe18afccb 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts @@ -11,6 +11,7 @@ import { tap } from 'rxjs'; import { omit } from 'lodash'; import type { Observable } from 'rxjs'; import { DataViewsService } from '@kbn/data-views-plugin/common'; +import type { SearchRequest } from '@elastic/elasticsearch/lib/api/types'; import { toSanitizedFieldType } from '../../../../common/fields_utils'; import type { FetchedIndexPattern, TrackedEsSearches } from '../../../../common/types'; @@ -20,8 +21,7 @@ import type { VisTypeTimeseriesVisDataRequest, } from '../../../types'; -export interface EsSearchRequest { - body: Record; +export interface EsSearchRequest extends SearchRequest { index?: string; trackingEsSearchMeta?: { requestId: string; @@ -47,18 +47,22 @@ export abstract class AbstractSearchStrategy { const searchContext = await requestContext.search; - esRequests.forEach(({ body, index, trackingEsSearchMeta }) => { + esRequests.forEach(({ body = {}, index, trackingEsSearchMeta, ...rest }) => { // User may abort the request without waiting for the results // we need to handle this scenario by aborting underlying server requests const abortSignal = getRequestAbortedSignal(req.events.aborted$); const startTime = Date.now(); + const searchBody = { + ...rest, + ...(typeof body === 'string' ? { body } : body), + }; requests.push( searchContext .search( { indexType, params: { - body, + ...searchBody, index, }, }, @@ -68,7 +72,7 @@ export abstract class AbstractSearchStrategy { tap((data) => { if (trackingEsSearchMeta?.requestId && trackedEsSearches) { trackedEsSearches[trackingEsSearchMeta.requestId] = { - body, + body: searchBody, time: Date.now() - startTime, label: trackingEsSearchMeta.requestLabel, response: omit(data.rawResponse, 'aggregations'), diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/annotations/get_request_params.ts b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/annotations/get_request_params.ts index c2b0a4771a327..6d89b627ddb5a 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/annotations/get_request_params.ts +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/annotations/get_request_params.ts @@ -66,11 +66,9 @@ export async function getAnnotationRequestParams( return { index: annotationIndex.indexPatternString, - body: { - ...request, - runtime_mappings: annotationIndex.indexPattern?.getComputedFields().runtimeFields ?? {}, - timeout: esShardTimeout > 0 ? `${esShardTimeout}ms` : undefined, - }, + ...request, + runtime_mappings: annotationIndex.indexPattern?.getComputedFields().runtimeFields ?? {}, + timeout: esShardTimeout > 0 ? `${esShardTimeout}ms` : undefined, trackingEsSearchMeta: { requestId: annotation.id, requestLabel: i18n.translate('visTypeTimeseries.annotationRequest.label', { diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/get_table_data.ts b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/get_table_data.ts index 3a7db5fd724de..e4bd46cc4316a 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/get_table_data.ts +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/get_table_data.ts @@ -98,19 +98,17 @@ export async function getTableData( const searches: EsSearchRequest[] = [ { index: panelIndex.indexPatternString, - body: { - ...(await buildTableRequest({ - req, - panel, - esQueryConfig: services.esQueryConfig, - seriesIndex: panelIndex, - capabilities, - uiSettings: services.uiSettings, - buildSeriesMetaParams: () => - services.buildSeriesMetaParams(panelIndex, Boolean(panel.use_kibana_indexes)), - })), - runtime_mappings: panelIndex.indexPattern?.getComputedFields().runtimeFields ?? {}, - }, + ...(await buildTableRequest({ + req, + panel, + esQueryConfig: services.esQueryConfig, + seriesIndex: panelIndex, + capabilities, + uiSettings: services.uiSettings, + buildSeriesMetaParams: () => + services.buildSeriesMetaParams(panelIndex, Boolean(panel.use_kibana_indexes)), + })), + runtime_mappings: panelIndex.indexPattern?.getComputedFields().runtimeFields ?? {}, trackingEsSearchMeta: { requestId: panel.id, requestLabel: i18n.translate('visTypeTimeseries.tableRequest.label', { diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js index bfa2aed4ea5da..efb80e9731eed 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js @@ -36,11 +36,9 @@ describe('ratios(req, panel, series, esQueryConfig, seriesIndex)', () => { ], }; req = { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }; esQueryConfig = { diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js index 91b60bdb6d10e..11b82472f71c5 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js @@ -15,11 +15,9 @@ describe('metricBuckets(req, panel, series)', () => { beforeEach(() => { metricBucketsProcessor = metricBuckets( { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }, { diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js index 31dd055c73a19..519c539c73b7f 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js @@ -38,11 +38,9 @@ describe('siblingBuckets(req, panel, series)', () => { ], }; req = { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }; uiSettings = { diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js index 6cb71e8fd21cc..249a862e964a3 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js @@ -17,11 +17,9 @@ describe('splitByEverything(req, panel, series)', () => { panel = {}; series = { id: 'test', split_mode: 'everything' }; req = { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }; }); diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js index bfc127fb68b7b..01fa01375ec2f 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js @@ -25,11 +25,9 @@ describe('splitByFilter(req, panel, series)', () => { filter: { query: 'host:example-01', language: 'lucene' }, }; req = { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }; seriesIndex = {}; diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js index 6dd71108a4f19..adf12b69a1ec9 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js @@ -41,11 +41,9 @@ describe('splitByFilters(req, panel, series)', () => { metrics: [{ id: 'avgmetric', type: 'avg', field: 'cpu' }], }; req = { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }; seriesIndex = {}; diff --git a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js index 474475e6b744f..d49f4645b7ca3 100644 --- a/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js +++ b/src/platform/plugins/shared/vis_types/timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js @@ -32,11 +32,9 @@ describe('splitByTerms', () => { metrics: [{ id: 'avgmetric', type: 'avg', field: 'cpu' }], }; req = { - body: { - timerange: { - min: '2017-01-01T00:00:00Z', - max: '2017-01-01T01:00:00Z', - }, + timerange: { + min: '2017-01-01T00:00:00Z', + max: '2017-01-01T01:00:00Z', }, }; seriesIndex = {}; diff --git a/test/api_integration/apis/data_view_field_editor/field_preview.ts b/test/api_integration/apis/data_view_field_editor/field_preview.ts index 24762ea2242e4..0498e9eee1f3b 100644 --- a/test/api_integration/apis/data_view_field_editor/field_preview.ts +++ b/test/api_integration/apis/data_view_field_editor/field_preview.ts @@ -31,15 +31,13 @@ export default function ({ getService }: FtrProviderContext) { const createIndex = async () => { await es.indices.create({ index: INDEX_NAME, - body: { - mappings: { - properties: { - foo: { - type: 'integer', - }, - bar: { - type: 'keyword', - }, + mappings: { + properties: { + foo: { + type: 'integer', + }, + bar: { + type: 'keyword', }, }, }, diff --git a/test/api_integration/apis/data_views/fields_for_wildcard_route/filter.ts b/test/api_integration/apis/data_views/fields_for_wildcard_route/filter.ts index 04574801a16c8..2750903e572ac 100644 --- a/test/api_integration/apis/data_views/fields_for_wildcard_route/filter.ts +++ b/test/api_integration/apis/data_views/fields_for_wildcard_route/filter.ts @@ -26,14 +26,14 @@ export default function ({ getService }: FtrProviderContext) { index: 'helloworld1', refresh: true, id: 'helloworld', - body: { hello: 'world' }, + document: { hello: 'world' }, }); await es.index({ index: 'helloworld2', refresh: true, id: 'helloworld2', - body: { bye: 'world' }, + document: { bye: 'world' }, }); }); diff --git a/test/api_integration/apis/esql/errors.ts b/test/api_integration/apis/esql/errors.ts index aff1c9e865406..afa0f52b7b7b4 100644 --- a/test/api_integration/apis/esql/errors.ts +++ b/test/api_integration/apis/esql/errors.ts @@ -229,12 +229,10 @@ export default function ({ getService }: FtrProviderContext) { await es.enrich.putPolicy( { name, - body: { - match: { - indices: sourceIndices, - match_field: matchField, - enrich_fields: enrichFields, - }, + match: { + indices: sourceIndices, + match_field: matchField, + enrich_fields: enrichFields, }, }, { ignore: [409] } diff --git a/test/api_integration/apis/saved_objects/delete_unknown_types.ts b/test/api_integration/apis/saved_objects/delete_unknown_types.ts index b03f6eebc3cfb..bcbf9e96dfee6 100644 --- a/test/api_integration/apis/saved_objects/delete_unknown_types.ts +++ b/test/api_integration/apis/saved_objects/delete_unknown_types.ts @@ -40,9 +40,7 @@ export default function ({ getService }: FtrProviderContext) { const fetchIndexContent = async () => { const body = await es.search<{ type: string }>({ index: [MAIN_SAVED_OBJECT_INDEX, ANALYTICS_SAVED_OBJECT_INDEX], - body: { - size: 100, - }, + size: 100, }); return body.hits.hits .map((hit) => ({ diff --git a/test/api_integration/apis/search/painless_err_req.ts b/test/api_integration/apis/search/painless_err_req.ts index 50aa232172488..d6e7e295be19a 100644 --- a/test/api_integration/apis/search/painless_err_req.ts +++ b/test/api_integration/apis/search/painless_err_req.ts @@ -10,35 +10,33 @@ export const painlessErrReq = { params: { index: 'log*', - body: { - size: 500, - fields: ['*'], - script_fields: { - invalid_scripted_field: { - script: { - source: 'invalid', - lang: 'painless', - }, + size: 500, + fields: ['*'], + script_fields: { + invalid_scripted_field: { + script: { + source: 'invalid', + lang: 'painless', }, }, - stored_fields: ['*'], - query: { - bool: { - filter: [ - { - match_all: {}, - }, - { - range: { - '@timestamp': { - gte: '2015-01-19T12:27:55.047Z', - lte: '2021-01-19T12:27:55.047Z', - format: 'strict_date_optional_time', - }, + }, + stored_fields: ['*'], + query: { + bool: { + filter: [ + { + match_all: {}, + }, + { + range: { + '@timestamp': { + gte: '2015-01-19T12:27:55.047Z', + lte: '2021-01-19T12:27:55.047Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, }, }, diff --git a/test/api_integration/apis/search/search.ts b/test/api_integration/apis/search/search.ts index 01609bec6f1b9..dd8c276421486 100644 --- a/test/api_integration/apis/search/search.ts +++ b/test/api_integration/apis/search/search.ts @@ -37,10 +37,8 @@ export default function ({ getService }: FtrProviderContext) { .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana') .send({ params: { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, }) @@ -63,10 +61,8 @@ export default function ({ getService }: FtrProviderContext) { terminateAfter: 1, index: 'log*', size: 1000, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, }) @@ -85,10 +81,8 @@ export default function ({ getService }: FtrProviderContext) { .set(ELASTIC_HTTP_VERSION_HEADER, '1') .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana') .send({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }) .expect(404); @@ -102,10 +96,8 @@ export default function ({ getService }: FtrProviderContext) { .set(ELASTIC_HTTP_VERSION_HEADER, '1') .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana') .send({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }) .expect(404); @@ -124,10 +116,8 @@ export default function ({ getService }: FtrProviderContext) { timeout: 1, // This should be a time range string! index: 'log*', size: 1000, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, }) diff --git a/test/functional/apps/discover/group5/_filter_editor.ts b/test/functional/apps/discover/group5/_filter_editor.ts index e2f568b8eb21d..828d64702c958 100644 --- a/test/functional/apps/discover/group5/_filter_editor.ts +++ b/test/functional/apps/discover/group5/_filter_editor.ts @@ -87,12 +87,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.indices.create({ index: indexTitle, - body: { - mappings: { - properties: { - version: { - type: 'version', - }, + mappings: { + properties: { + version: { + type: 'version', }, }, }, @@ -100,7 +98,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.index({ index: indexTitle, - body: { + document: { version: '1.0.0', }, refresh: 'wait_for', @@ -108,7 +106,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.index({ index: indexTitle, - body: { + document: { version: '2.0.0', }, refresh: 'wait_for', diff --git a/test/functional/apps/management/data_views/_field_formatter.ts b/test/functional/apps/management/data_views/_field_formatter.ts index 94f0b671490f6..4f21d9999ee8c 100644 --- a/test/functional/apps/management/data_views/_field_formatter.ts +++ b/test/functional/apps/management/data_views/_field_formatter.ts @@ -431,18 +431,16 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should apply default formatter by field meta value', async () => { await es.indices.create({ index: indexTitle, - body: { - mappings: { - properties: { - seconds: { type: 'long', meta: { unit: 's' } }, - }, + mappings: { + properties: { + seconds: { type: 'long', meta: { unit: 's' } }, }, }, }); const docResult = await es.index({ index: indexTitle, - body: { seconds: 1234 }, + document: { seconds: 1234 }, refresh: 'wait_for', }); @@ -482,20 +480,18 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.indices.create({ index: indexTitle, - body: { - mappings: { - // @ts-expect-error Type 'Record' is not assignable to type 'Record'. - properties: specs.reduce((properties, spec, index) => { - properties[`${index}`] = { type: spec.fieldType }; - return properties; - }, {} as Record), - }, + mappings: { + // @ts-expect-error Type 'Record' is not assignable to type 'Record'. + properties: specs.reduce((properties, spec, index) => { + properties[`${index}`] = { type: spec.fieldType }; + return properties; + }, {} as Record), }, }); const docResult = await es.index({ index: indexTitle, - body: specs.reduce((properties, spec, index) => { + document: specs.reduce((properties, spec, index) => { properties[`${index}`] = spec.fieldValue; return properties; }, {} as Record), diff --git a/test/functional/apps/management/data_views/_handle_alias.ts b/test/functional/apps/management/data_views/_handle_alias.ts index ca9f2b1f8cfea..a5f07e32c979d 100644 --- a/test/functional/apps/management/data_views/_handle_alias.ts +++ b/test/functional/apps/management/data_views/_handle_alias.ts @@ -24,19 +24,17 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await security.testUser.setRoles(['kibana_admin', 'test_alias_reader']); await esArchiver.loadIfNeeded('test/functional/fixtures/es_archiver/alias'); await es.indices.updateAliases({ - body: { - actions: [ - { add: { index: 'test1', alias: 'alias1' } }, - { add: { index: 'test2', alias: 'alias1' } }, - { add: { index: 'test3', alias: 'alias1' } }, - { add: { index: 'test4', alias: 'alias1' } }, - { add: { index: 'test5', alias: 'alias2' } }, - { add: { index: 'test6', alias: 'alias2' } }, - { add: { index: 'test7', alias: 'alias2' } }, - { add: { index: 'test8', alias: 'alias2' } }, - { add: { index: 'test9', alias: 'alias2' } }, - ], - }, + actions: [ + { add: { index: 'test1', alias: 'alias1' } }, + { add: { index: 'test2', alias: 'alias1' } }, + { add: { index: 'test3', alias: 'alias1' } }, + { add: { index: 'test4', alias: 'alias1' } }, + { add: { index: 'test5', alias: 'alias2' } }, + { add: { index: 'test6', alias: 'alias2' } }, + { add: { index: 'test7', alias: 'alias2' } }, + { add: { index: 'test8', alias: 'alias2' } }, + { add: { index: 'test9', alias: 'alias2' } }, + ], }); }); diff --git a/test/functional/apps/management/data_views/_handle_version_conflict.ts b/test/functional/apps/management/data_views/_handle_version_conflict.ts index 8853d43d06c69..6f1398a1ac34e 100644 --- a/test/functional/apps/management/data_views/_handle_version_conflict.ts +++ b/test/functional/apps/management/data_views/_handle_version_conflict.ts @@ -51,9 +51,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { { index: ANALYTICS_SAVED_OBJECT_INDEX, id: 'index-pattern:logstash-*', - body: { - doc: { 'index-pattern': { fieldFormatMap: '{"geo.src":{"id":"number"}}' } }, - }, + doc: { 'index-pattern': { fieldFormatMap: '{"geo.src":{"id":"number"}}' } }, }, { meta: true } ); @@ -81,9 +79,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { { index: ANALYTICS_SAVED_OBJECT_INDEX, id: 'index-pattern:logstash-*', - body: { - doc: { 'index-pattern': { fieldFormatMap: '{"geo.dest":{"id":"number"}}' } }, - }, + doc: { 'index-pattern': { fieldFormatMap: '{"geo.dest":{"id":"number"}}' } }, }, { meta: true } ); diff --git a/test/functional/apps/management/data_views/_index_pattern_filter.ts b/test/functional/apps/management/data_views/_index_pattern_filter.ts index a2cab2d735c9d..efdc098f037ee 100644 --- a/test/functional/apps/management/data_views/_index_pattern_filter.ts +++ b/test/functional/apps/management/data_views/_index_pattern_filter.ts @@ -150,12 +150,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.indices.create({ index: additionalIndexWithWrongMapping, - body: { - mappings: { - properties: { - bytes: { - type: 'keyword', - }, + mappings: { + properties: { + bytes: { + type: 'keyword', }, }, }, @@ -163,7 +161,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.index({ index: additionalIndexWithWrongMapping, - body: { + document: { bytes: 'wrong_value', }, refresh: 'wait_for', diff --git a/test/interactive_setup_api_integration/tests/enrollment_flow.ts b/test/interactive_setup_api_integration/tests/enrollment_flow.ts index 701d7109e3a54..97f9d4bcc10fc 100644 --- a/test/interactive_setup_api_integration/tests/enrollment_flow.ts +++ b/test/interactive_setup_api_integration/tests/enrollment_flow.ts @@ -38,12 +38,12 @@ export default function (context: FtrProviderContext) { let enrollmentAPIKey: string; beforeEach(async () => { - const apiResponse = await es.security.createApiKey({ body: { name: 'enrollment_api_key' } }); + const apiResponse = await es.security.createApiKey({ name: 'enrollment_api_key' }); enrollmentAPIKey = Buffer.from(`${apiResponse.id}:${apiResponse.api_key}`).toString('base64'); }); afterEach(async () => { - await es.security.invalidateApiKey({ body: { name: 'enrollment_api_key' } }); + await es.security.invalidateApiKey({ name: 'enrollment_api_key' }); }); it('fails to enroll with invalid authentication code', async () => { @@ -99,7 +99,7 @@ export default function (context: FtrProviderContext) { log.debug(`Enroll payload ${JSON.stringify(enrollPayload)}`); // Invalidate API key. - await es.security.invalidateApiKey({ body: { name: 'enrollment_api_key' } }); + await es.security.invalidateApiKey({ name: 'enrollment_api_key' }); await supertest .post('/internal/interactive_setup/enroll') diff --git a/test/interactive_setup_functional/tests/enrollment_token.ts b/test/interactive_setup_functional/tests/enrollment_token.ts index 8ce7189955d52..50fb59a590073 100644 --- a/test/interactive_setup_functional/tests/enrollment_token.ts +++ b/test/interactive_setup_functional/tests/enrollment_token.ts @@ -43,13 +43,13 @@ export default function ({ getService }: FtrProviderContext) { let enrollmentAPIKey: string; beforeEach(async function () { - const apiResponse = await es.security.createApiKey({ body: { name: 'enrollment_api_key' } }); + const apiResponse = await es.security.createApiKey({ name: 'enrollment_api_key' }); enrollmentAPIKey = `${apiResponse.id}:${apiResponse.api_key}`; log.info(`API key for enrollment token: ${enrollmentAPIKey}`); }); afterEach(async function () { - await es.security.invalidateApiKey({ body: { name: 'enrollment_api_key' } }); + await es.security.invalidateApiKey({ name: 'enrollment_api_key' }); }); it('should configure Kibana successfully', async function () { diff --git a/x-pack/packages/ai-infra/product-doc-artifact-builder/src/build_artifacts.ts b/x-pack/packages/ai-infra/product-doc-artifact-builder/src/build_artifacts.ts index a929cb62d0bb4..805f35c4460ae 100644 --- a/x-pack/packages/ai-infra/product-doc-artifact-builder/src/build_artifacts.ts +++ b/x-pack/packages/ai-infra/product-doc-artifact-builder/src/build_artifacts.ts @@ -6,7 +6,7 @@ */ import Path from 'path'; -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { ToolingLog } from '@kbn/tooling-log'; import type { ProductName } from '@kbn/product-doc-common'; import { @@ -31,6 +31,8 @@ const getSourceClient = (config: TaskConfig) => { username: config.sourceClusterUsername, password: config.sourceClusterPassword, }, + Connection: HttpConnection, + requestTimeout: 30_000, }); }; @@ -44,6 +46,7 @@ const getEmbeddingClient = (config: TaskConfig) => { }, // generating embeddings takes time requestTimeout: 10 * 60 * 1000, + Connection: HttpConnection, }); }; diff --git a/x-pack/platform/packages/private/kbn-infra-forge/src/lib/manage_template.ts b/x-pack/platform/packages/private/kbn-infra-forge/src/lib/manage_template.ts index 722d1cb0b8ac4..25e4c5671d841 100644 --- a/x-pack/platform/packages/private/kbn-infra-forge/src/lib/manage_template.ts +++ b/x-pack/platform/packages/private/kbn-infra-forge/src/lib/manage_template.ts @@ -22,7 +22,7 @@ export async function installTemplate( await client.cluster .putComponentTemplate({ name: component.name, - ...component.template, + ...(component.template as Omit), }) .catch((error) => logger.error(`Failed installing component > ${JSON.stringify(error)}`)); } diff --git a/x-pack/platform/packages/private/kbn-infra-forge/src/lib/queue.ts b/x-pack/platform/packages/private/kbn-infra-forge/src/lib/queue.ts index 75f3affb743d3..6970f7da033d1 100644 --- a/x-pack/platform/packages/private/kbn-infra-forge/src/lib/queue.ts +++ b/x-pack/platform/packages/private/kbn-infra-forge/src/lib/queue.ts @@ -24,17 +24,17 @@ export const createQueue = ( logger.debug(`createQueue > index name: ${indexName}`); return async.cargoQueue( (docs: object[], callback) => { - const body: object[] = []; + const operations: object[] = []; docs.forEach((doc) => { - body.push({ + operations.push({ create: { _index: indexName, }, }); - body.push(omit(doc, 'namespace')); + operations.push(omit(doc, 'namespace')); }); esClient - .bulk({ body, refresh: true }) + .bulk({ operations, refresh: true }) .then((resp) => { if (resp.errors) { logger.error( diff --git a/x-pack/platform/packages/private/ml/agg_utils/src/build_sampler_aggregation.ts b/x-pack/platform/packages/private/ml/agg_utils/src/build_sampler_aggregation.ts index fa554001c8954..d96ec4c29a465 100644 --- a/x-pack/platform/packages/private/ml/agg_utils/src/build_sampler_aggregation.ts +++ b/x-pack/platform/packages/private/ml/agg_utils/src/build_sampler_aggregation.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; /** * Wraps the supplied aggregations in a sampler aggregation. diff --git a/x-pack/platform/packages/private/ml/agg_utils/src/fetch_agg_intervals.ts b/x-pack/platform/packages/private/ml/agg_utils/src/fetch_agg_intervals.ts index f10977073f9bf..299b09205cecc 100644 --- a/x-pack/platform/packages/private/ml/agg_utils/src/fetch_agg_intervals.ts +++ b/x-pack/platform/packages/private/ml/agg_utils/src/fetch_agg_intervals.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import { KBN_FIELD_TYPES } from '@kbn/field-types'; @@ -102,15 +102,12 @@ export const fetchAggIntervals = async ( { index: indexPattern, size: 0, - body: { - query, - aggs: - randomSamplerProbability === undefined - ? buildSamplerAggregation(minMaxAggs, samplerShardSize) - : wrap(minMaxAggs), - size: 0, - ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), - }, + query, + aggs: + randomSamplerProbability === undefined + ? buildSamplerAggregation(minMaxAggs, samplerShardSize) + : wrap(minMaxAggs), + ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), }, { signal: abortSignal, maxRetries: 0 } ); diff --git a/x-pack/platform/packages/private/ml/agg_utils/src/fetch_histograms_for_fields.ts b/x-pack/platform/packages/private/ml/agg_utils/src/fetch_histograms_for_fields.ts index 4646b390f6d2b..2318c999504f3 100644 --- a/x-pack/platform/packages/private/ml/agg_utils/src/fetch_histograms_for_fields.ts +++ b/x-pack/platform/packages/private/ml/agg_utils/src/fetch_histograms_for_fields.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import { KBN_FIELD_TYPES } from '@kbn/field-types'; @@ -286,15 +286,12 @@ export const fetchHistogramsForFields = async (params: FetchHistogramsForFieldsP { index: indexPattern, size: 0, - body: { - query, - aggs: - randomSamplerProbability === undefined - ? buildSamplerAggregation(chartDataAggs, samplerShardSize) - : wrap(chartDataAggs), - size: 0, - ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), - }, + query, + aggs: + randomSamplerProbability === undefined + ? buildSamplerAggregation(chartDataAggs, samplerShardSize) + : wrap(chartDataAggs), + ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), }, { signal: abortSignal, maxRetries: 0 } ); diff --git a/x-pack/platform/packages/private/ml/agg_utils/src/is_multi_bucket_aggregate.ts b/x-pack/platform/packages/private/ml/agg_utils/src/is_multi_bucket_aggregate.ts index 549df558d4947..6c4c3193f7c76 100644 --- a/x-pack/platform/packages/private/ml/agg_utils/src/is_multi_bucket_aggregate.ts +++ b/x-pack/platform/packages/private/ml/agg_utils/src/is_multi_bucket_aggregate.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; /** diff --git a/x-pack/platform/packages/private/ml/category_validator/common/types/categories.ts b/x-pack/platform/packages/private/ml/category_validator/common/types/categories.ts index 538f326517488..29a4f0d861bfc 100644 --- a/x-pack/platform/packages/private/ml/category_validator/common/types/categories.ts +++ b/x-pack/platform/packages/private/ml/category_validator/common/types/categories.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { CATEGORY_EXAMPLES_VALIDATION_STATUS, diff --git a/x-pack/platform/packages/private/ml/category_validator/src/examples.ts b/x-pack/platform/packages/private/ml/category_validator/src/examples.ts index 860ed80ed1060..c3a749c3d8bc4 100644 --- a/x-pack/platform/packages/private/ml/category_validator/src/examples.ts +++ b/x-pack/platform/packages/private/ml/category_validator/src/examples.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { chunk } from 'lodash'; import type { IScopedClusterClient } from '@kbn/core/server'; @@ -90,13 +90,11 @@ export function categorizationExamplesProvider(client: IScopedClusterClient) { { index: indexPatternTitle, size, - body: { - fields: [categorizationFieldName], - _source: false, - query, - sort: ['_doc'], - ...(runtimeMappings !== undefined ? { runtime_mappings: runtimeMappings } : {}), - }, + fields: [categorizationFieldName], + _source: false, + query, + sort: ['_doc'], + ...(runtimeMappings !== undefined ? { runtime_mappings: runtimeMappings } : {}), ...(indicesOptions ?? {}), }, { maxRetries: 0 } @@ -155,10 +153,8 @@ export function categorizationExamplesProvider(client: IScopedClusterClient) { async function loadTokens(examples: string[], analyzer: CategorizationAnalyzer) { const { tokens } = await asInternalUser.indices.analyze( { - body: { - ...getAnalyzer(analyzer), - text: examples, - }, + ...getAnalyzer(analyzer), + text: examples, }, { maxRetries: 0 } ); diff --git a/x-pack/platform/packages/private/ml/data_frame_analytics_utils/src/types.ts b/x-pack/platform/packages/private/ml/data_frame_analytics_utils/src/types.ts index 3b47801ba0231..85532be1d33cc 100644 --- a/x-pack/platform/packages/private/ml/data_frame_analytics_utils/src/types.ts +++ b/x-pack/platform/packages/private/ml/data_frame_analytics_utils/src/types.ts @@ -6,7 +6,7 @@ */ import type Boom from '@hapi/boom'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import type { EsErrorBody } from '@kbn/ml-error-utils'; diff --git a/x-pack/platform/packages/private/ml/data_grid/lib/common.ts b/x-pack/platform/packages/private/ml/data_grid/lib/common.ts index d364998f83af7..a28df94887c49 100644 --- a/x-pack/platform/packages/private/ml/data_grid/lib/common.ts +++ b/x-pack/platform/packages/private/ml/data_grid/lib/common.ts @@ -8,7 +8,7 @@ import moment from 'moment-timezone'; import { useMemo } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiDataGridCellValueElementProps, EuiDataGridStyle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/platform/packages/private/ml/data_grid/lib/types.ts b/x-pack/platform/packages/private/ml/data_grid/lib/types.ts index a652e92d4c522..2f68b3cfb1e44 100644 --- a/x-pack/platform/packages/private/ml/data_grid/lib/types.ts +++ b/x-pack/platform/packages/private/ml/data_grid/lib/types.ts @@ -7,7 +7,7 @@ import type { Dispatch, SetStateAction } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiDataGridCellValueElementProps, EuiDataGridPaginationProps, diff --git a/x-pack/platform/packages/private/ml/date_picker/src/services/time_field_range.ts b/x-pack/platform/packages/private/ml/date_picker/src/services/time_field_range.ts index f935c4577b394..c40a2ff750214 100644 --- a/x-pack/platform/packages/private/ml/date_picker/src/services/time_field_range.ts +++ b/x-pack/platform/packages/private/ml/date_picker/src/services/time_field_range.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { HttpStart } from '@kbn/core/public'; diff --git a/x-pack/platform/packages/private/ml/field_stats_flyout/populated_fields/get_range_filter.ts b/x-pack/platform/packages/private/ml/field_stats_flyout/populated_fields/get_range_filter.ts index c58ae2087f0d7..a58820fe4fece 100644 --- a/x-pack/platform/packages/private/ml/field_stats_flyout/populated_fields/get_range_filter.ts +++ b/x-pack/platform/packages/private/ml/field_stats_flyout/populated_fields/get_range_filter.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TimeRange as TimeRangeMs } from '@kbn/ml-date-picker'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts b/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts index 6225e0b615ef2..ee7fed9383ba9 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Query } from '@kbn/es-query'; import { isDefaultQuery } from './default_query'; diff --git a/x-pack/platform/packages/private/ml/query_utils/src/es_client_total_hits_relation.ts b/x-pack/platform/packages/private/ml/query_utils/src/es_client_total_hits_relation.ts index 0c5e6a6fd8e5d..08870e64996b7 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/es_client_total_hits_relation.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/es_client_total_hits_relation.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; /** * Custom enum for total hits relation values diff --git a/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts b/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts index 08ed5bb94ddaa..d62cc97f92c48 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts @@ -7,7 +7,7 @@ import { cloneDeep } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; const DEFAULT_DSL_QUERY: estypes.QueryDslQueryContainer = { bool: { diff --git a/x-pack/platform/packages/private/ml/query_utils/src/types.ts b/x-pack/platform/packages/private/ml/query_utils/src/types.ts index 49e46d1f8be61..d743123b03560 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/types.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; /** * Constant for kuery and lucene string diff --git a/x-pack/platform/packages/private/ml/ui_actions/src/ml/ui_actions.ts b/x-pack/platform/packages/private/ml/ui_actions/src/ml/ui_actions.ts index cf36e3ff01ce6..b9fb6536faa7f 100644 --- a/x-pack/platform/packages/private/ml/ui_actions/src/ml/ui_actions.ts +++ b/x-pack/platform/packages/private/ml/ui_actions/src/ml/ui_actions.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { DataView, DataViewField } from '@kbn/data-views-plugin/common'; import type { TimeRange } from '@kbn/es-query'; diff --git a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/get_es_client.ts b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/get_es_client.ts index 6244a09063722..eebf61589f612 100644 --- a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/get_es_client.ts +++ b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/get_es_client.ts @@ -6,7 +6,7 @@ */ import * as Fs from 'fs'; -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { CA_CERT_PATH } from '@kbn/dev-utils'; import { Config } from '../types'; @@ -35,6 +35,8 @@ export const getEsClient = (config: Config) => { rejectUnauthorized: false, } : undefined, + Connection: HttpConnection, + requestTimeout: 30_000, }); return esClient; diff --git a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_default_component_template.ts b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_default_component_template.ts index 65c3dc3f1e44d..4f1b930ea8403 100644 --- a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_default_component_template.ts +++ b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_default_component_template.ts @@ -20,7 +20,7 @@ const eventIngestedCommonComponentTemplate = { event: { properties: { ingested: { - type: 'date', + type: 'date' as const, }, }, }, diff --git a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_index_template.ts b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_index_template.ts index 645089aa64ac2..2005c05140200 100644 --- a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_index_template.ts +++ b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/install_index_template.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; -import { ToolingLog } from '@kbn/tooling-log'; +import type { Client } from '@elastic/elasticsearch'; +import type { ToolingLog } from '@kbn/tooling-log'; import { isArray } from 'lodash'; import { indexTemplates } from '../data_sources'; -import { Config } from '../types'; +import type { Config, IndexTemplateDef } from '../types'; export async function installIndexTemplate( config: Config, @@ -24,7 +24,10 @@ export async function installIndexTemplate( const componentNames = indexTemplateDef.components.map(({ name }) => name); logger.info(`Installing components for ${indexTemplateDef.name} (${componentNames})`); for (const component of indexTemplateDef.components) { - await client.cluster.putComponentTemplate({ name: component.name, ...component.template }); + await client.cluster.putComponentTemplate({ + name: component.name, + ...(component.template as Omit), + }); } logger.info(`Installing index template (${indexTemplateDef.name})`); // Clone the template and add the base component name diff --git a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/queue.ts b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/queue.ts index d5bc892b49b23..d51e39022cb45 100644 --- a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/queue.ts +++ b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/queue.ts @@ -33,16 +33,16 @@ export const createQueue = (config: Config, client: Client, logger: ToolingLog): if (queue != null) return queue; queue = cargoQueue( (docs, callback) => { - const body: object[] = []; + const operations: object[] = []; const startTs = Date.now(); docs.forEach((doc) => { const indexName = calculateIndexName(config, doc); indices.add(indexName); - body.push({ create: { _index: indexName } }); - body.push(omit(doc, 'namespace')); + operations.push({ create: { _index: indexName } }); + operations.push(omit(doc, 'namespace')); }); client - .bulk({ body, refresh: false }) + .bulk({ operations, refresh: false }) .then((resp) => { if (resp.errors) { logger.error(`Failed to index: ${resp.errors}`); diff --git a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/setup_kibana_system_user.ts b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/setup_kibana_system_user.ts index a74e65c0b8915..f3bb1c656d8a1 100644 --- a/x-pack/platform/packages/shared/kbn-data-forge/src/lib/setup_kibana_system_user.ts +++ b/x-pack/platform/packages/shared/kbn-data-forge/src/lib/setup_kibana_system_user.ts @@ -12,7 +12,7 @@ import { Config } from '../types'; export async function setupKibanaSystemUser(config: Config, client: Client, logger: ToolingLog) { await client.security - .changePassword({ username: 'kibana_system', body: { password: 'changeme' } }) + .changePassword({ username: 'kibana_system', password: 'changeme' }) .then(() => { logger.info('Password changed to "changeme" for "kibana_system" user'); }) diff --git a/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.test.ts b/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.test.ts index 72c6977569e16..24f0fc01f139b 100644 --- a/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.test.ts +++ b/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.test.ts @@ -41,66 +41,61 @@ describe('getOpenAndAcknowledgedAlertsQuery', () => { expect(query).toEqual({ allow_no_indices: true, - body: { - fields: [ - { field: 'field1', include_unmapped: true }, - { field: 'field2', include_unmapped: true }, - ], - query: { - bool: { - filter: [ - { - bool: { - must: [], - filter: [ - { - bool: { - should: [ - { - match_phrase: { - 'kibana.alert.workflow_status': 'open', - }, + fields: [ + { field: 'field1', include_unmapped: true }, + { field: 'field2', include_unmapped: true }, + ], + query: { + bool: { + filter: [ + { + bool: { + must: [], + filter: [ + { + bool: { + should: [ + { + match_phrase: { + 'kibana.alert.workflow_status': 'open', }, - { - match_phrase: { - 'kibana.alert.workflow_status': 'acknowledged', - }, + }, + { + match_phrase: { + 'kibana.alert.workflow_status': 'acknowledged', }, - ], - minimum_should_match: 1, - }, - }, - { - range: { - '@timestamp': { - gte: 'now-24h', - lte: 'now', - format: 'strict_date_optional_time', }, - }, + ], + minimum_should_match: 1, }, - ], - should: [], - must_not: [ - { - exists: { - field: 'kibana.alert.building_block_type', + }, + { + range: { + '@timestamp': { + gte: 'now-24h', + lte: 'now', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], + should: [], + must_not: [ + { + exists: { + field: 'kibana.alert.building_block_type', + }, + }, + ], }, - ], - }, + }, + ], }, - runtime_mappings: {}, - size: 10, - sort: [ - { 'kibana.alert.risk_score': { order: 'desc' } }, - { '@timestamp': { order: 'desc' } }, - ], - _source: false, }, + runtime_mappings: {}, + size: 10, + sort: [{ 'kibana.alert.risk_score': { order: 'desc' } }, { '@timestamp': { order: 'desc' } }], + _source: false, ignore_unavailable: true, index: ['alerts-*'], }); @@ -135,7 +130,7 @@ describe('getOpenAndAcknowledgedAlertsQuery', () => { size, }); - expect(query.body.query.bool.filter).toEqual([ + expect(query.query.bool.filter).toEqual([ { bool: { must: [], @@ -192,7 +187,7 @@ describe('getOpenAndAcknowledgedAlertsQuery', () => { }); const rangeFilter: MaybeHasRange | undefined = ( - query.body.query.bool.filter[0].bool as MaybeHasFilter + query.query.bool.filter[0].bool as MaybeHasFilter ).filter?.find((x) => Object.hasOwn(x, 'range')); const timestamp: MaybeTimestampValues | undefined = rangeFilter?.range?.['@timestamp']; @@ -211,7 +206,7 @@ describe('getOpenAndAcknowledgedAlertsQuery', () => { }); const rangeFilter: MaybeHasRange | undefined = ( - query.body.query.bool.filter[0].bool as MaybeHasFilter + query.query.bool.filter[0].bool as MaybeHasFilter ).filter?.find((x) => Object.hasOwn(x, 'range')); const timestamp: MaybeTimestampValues | undefined = rangeFilter?.range?.['@timestamp']; diff --git a/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.ts b/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.ts index c275b9e640c3f..0a58d69c4d885 100644 --- a/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.ts +++ b/x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/alerts/get_open_and_acknowledged_alerts_query/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import type { AnonymizationFieldResponse } from '../../schemas/anonymization_fields/bulk_crud_anonymization_fields_route.gen'; export const DEFAULT_END = 'now'; @@ -12,25 +13,23 @@ export const DEFAULT_START = 'now-24h'; interface GetOpenAndAcknowledgedAlertsQuery { allow_no_indices: boolean; - body: { - fields: Array<{ - field: string; - include_unmapped: boolean; - }>; - query: { - bool: { - filter: Array>; - }; + fields: Array<{ + field: string; + include_unmapped: boolean; + }>; + query: { + bool: { + filter: Array>; }; - runtime_mappings: Record; - size: number; - sort: Array<{ - [key: string]: { - order: string; - }; - }>; - _source: boolean; }; + runtime_mappings: MappingRuntimeFields; + size: number; + sort: Array<{ + [key: string]: { + order: 'desc' | 'asc'; + }; + }>; + _source: boolean; ignore_unavailable: boolean; index: string[]; } @@ -56,77 +55,75 @@ export const getOpenAndAcknowledgedAlertsQuery = ({ start?: string | null; }): GetOpenAndAcknowledgedAlertsQuery => ({ allow_no_indices: true, - body: { - fields: anonymizationFields - .filter((fieldItem) => fieldItem.allowed) - .map((fieldItem) => ({ - field: fieldItem.field, - include_unmapped: true, - })), - query: { - bool: { - filter: [ - { - bool: { - must: [], - filter: [ - { - bool: { - should: [ - { - match_phrase: { - 'kibana.alert.workflow_status': 'open', - }, + fields: anonymizationFields + .filter((fieldItem) => fieldItem.allowed) + .map((fieldItem) => ({ + field: fieldItem.field, + include_unmapped: true, + })), + query: { + bool: { + filter: [ + { + bool: { + must: [], + filter: [ + { + bool: { + should: [ + { + match_phrase: { + 'kibana.alert.workflow_status': 'open', }, - { - match_phrase: { - 'kibana.alert.workflow_status': 'acknowledged', - }, + }, + { + match_phrase: { + 'kibana.alert.workflow_status': 'acknowledged', }, - ], - minimum_should_match: 1, - }, - }, - ...(filter != null ? [filter] : []), - { - range: { - '@timestamp': { - gte: start != null ? start : DEFAULT_START, - lte: end != null ? end : DEFAULT_END, - format: 'strict_date_optional_time', }, - }, + ], + minimum_should_match: 1, }, - ], - should: [], - must_not: [ - { - exists: { - field: 'kibana.alert.building_block_type', + }, + ...(filter != null ? [filter] : []), + { + range: { + '@timestamp': { + gte: start != null ? start : DEFAULT_START, + lte: end != null ? end : DEFAULT_END, + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], + should: [], + must_not: [ + { + exists: { + field: 'kibana.alert.building_block_type', + }, + }, + ], }, - ], - }, - }, - runtime_mappings: {}, - size, - sort: [ - { - 'kibana.alert.risk_score': { - order: 'desc', }, + ], + }, + }, + runtime_mappings: {}, + size, + sort: [ + { + 'kibana.alert.risk_score': { + order: 'desc', }, - { - '@timestamp': { - order: 'desc', - }, + }, + { + '@timestamp': { + order: 'desc', }, - ], - _source: false, - }, + }, + ], + _source: false, ignore_unavailable: true, index: [alertsIndexPattern], }); diff --git a/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.test.tsx b/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.test.tsx index 044b1cc84adec..7d681b33dc026 100644 --- a/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.test.tsx +++ b/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/types'; import { useInferenceEndpointMutation } from './use_inference_endpoint_mutation'; import { act, renderHook } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; diff --git a/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.ts b/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.ts index e540b0d44c8ce..2d510cebe66c0 100644 --- a/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.ts +++ b/x-pack/platform/packages/shared/kbn-inference-endpoint-ui-common/src/hooks/use_inference_endpoint_mutation.ts @@ -9,7 +9,7 @@ import type { HttpSetup } from '@kbn/core-http-browser'; import { useMutation } from '@tanstack/react-query'; import { KibanaServerError } from '@kbn/kibana-utils-plugin/common'; import { IToasts } from '@kbn/core/public'; -import { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/types'; import * as i18n from '../translations'; import { INFERENCE_ENDPOINT_INTERNAL_API_VERSION, InferenceEndpoint } from '../types/types'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/create_category_request.ts b/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/create_category_request.ts index 4e8e2268fed5a..33ddafa83d818 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/create_category_request.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/create_category_request.ts @@ -6,7 +6,7 @@ */ import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import { isPopulatedObject } from '@kbn/ml-is-populated-object/src/is_populated_object'; import type { createRandomSamplerWrapper } from '@kbn/ml-random-sampler-utils'; @@ -110,12 +110,10 @@ export function createCategoryRequest( return { params: { index, - body: { - query, - aggs: wrap(aggs), - ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), - size: 0, - }, + query, + aggs: wrap(aggs), + ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), + size: 0, }, }; } diff --git a/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/get_category_query.ts b/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/get_category_query.ts index 9c7581c4742ef..93e7f19d2224f 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/get_category_query.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_pattern_analysis/get_category_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Category } from './types'; export const QUERY_MODE = { diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.test.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.test.ts index 64477ab64aff9..5dfba44f6eb6a 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.test.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.test.ts @@ -67,57 +67,55 @@ describe('getCategoryRequest', () => { // time range filter whatsoever, for example for start/end (0,50). expect(query).toEqual({ index: 'the-index', - body: { - query: { - bool: { - filter: [ - { - bool: { - should: [ - { - range: { - 'the-time-field-name': { - gte: 10, - lte: 20, - format: 'epoch_millis', - }, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { + range: { + 'the-time-field-name': { + gte: 10, + lte: 20, + format: 'epoch_millis', }, }, - { - range: { - 'the-time-field-name': { - gte: 30, - lte: 40, - format: 'epoch_millis', - }, + }, + { + range: { + 'the-time-field-name': { + gte: 30, + lte: 40, + format: 'epoch_millis', }, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - aggs: { - sample: { - random_sampler: { probability: 0.1, seed: 1234 }, - aggs: { - categories: { - categorize_text: { - field: 'the-field-name', - size: 1000, - }, - aggs: { - examples: { - top_hits: { size: 4, sort: ['the-time-field-name'], _source: 'the-field-name' }, - }, + }, + aggs: { + sample: { + random_sampler: { probability: 0.1, seed: 1234 }, + aggs: { + categories: { + categorize_text: { + field: 'the-field-name', + size: 1000, + }, + aggs: { + examples: { + top_hits: { size: 4, sort: ['the-time-field-name'], _source: 'the-field-name' }, }, }, }, }, }, - size: 0, }, + size: 0, }); }); }); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.ts index 2a06b36a9fac4..48967d9f39240 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_categories.ts @@ -5,8 +5,8 @@ * 2.0. */ -import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { get, omit } from 'lodash'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { Logger } from '@kbn/logging'; @@ -91,7 +91,7 @@ export const getCategoryRequest = ( // In this case we're only interested in the aggregation which // `createCategoryRequest` returns, so we're re-applying the original // query we create via `getQueryWithParams` here. - request.body.query = query; + request.query = query; return request; }; @@ -119,8 +119,7 @@ export const fetchCategories = async ( const searches: estypes.MsearchRequestItem[] = fieldNames.flatMap((fieldName) => [ { index: params.index }, - getCategoryRequest(params, fieldName, randomSamplerWrapper) - .body as estypes.MsearchMultisearchBody, + omit(getCategoryRequest(params, fieldName, randomSamplerWrapper), ['index']), ]); let mSearchResponse; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.test.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.test.ts index 1593bf7dd5b18..f40e9c0a95f92 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.test.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.test.ts @@ -28,33 +28,31 @@ describe('getCategoryCountRequest', () => { expect(query).toEqual({ index: 'the-index', - body: { - query: { - bool: { - filter: [ - { range: { 'the-time-field-name': { gte: 10, lte: 20, format: 'epoch_millis' } } }, - { - bool: { - should: [ - { - match: { - 'the-field-name': { - auto_generate_synonyms_phrase_query: false, - fuzziness: 0, - operator: 'and', - query: 'runTask ended no files to process', - }, + query: { + bool: { + filter: [ + { range: { 'the-time-field-name': { gte: 10, lte: 20, format: 'epoch_millis' } } }, + { + bool: { + should: [ + { + match: { + 'the-field-name': { + auto_generate_synonyms_phrase_query: false, + fuzziness: 0, + operator: 'and', + query: 'runTask ended no files to process', }, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - size: 0, - track_total_hits: true, }, + size: 0, + track_total_hits: true, }); }); }); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.ts index 0fe63259f6280..c5a80baa80e30 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_category_counts.ts @@ -5,8 +5,8 @@ * 2.0. */ -import { cloneDeep } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { cloneDeep, omit } from 'lodash'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { Logger } from '@kbn/logging'; @@ -47,11 +47,9 @@ export const getCategoryCountRequest = ( return { index, - body: { - query, - size: 0, - track_total_hits: true, - }, + query, + size: 0, + track_total_hits: true, }; }; @@ -64,8 +62,7 @@ export const getCategoryCountMSearchRequest = ( ): estypes.MsearchRequestItem[] => categories.flatMap((category) => [ { index: params.index }, - getCategoryCountRequest(params, fieldName, category, from, to) - .body as estypes.MsearchMultisearchBody, + omit(getCategoryCountRequest(params, fieldName, category, from, to), ['index']), ]); export const fetchCategoryCounts = async ( diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_frequent_item_sets.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_frequent_item_sets.ts index 34c34482ccf7c..1809395174054 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_frequent_item_sets.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_frequent_item_sets.ts @@ -8,7 +8,7 @@ import { uniq, pick, isEqual } from 'lodash'; import { group } from 'd3-array'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import type { Logger } from '@kbn/logging'; @@ -164,8 +164,7 @@ export async function fetchFrequentItemSets({ >( { index, - size: 0, - body: esBody, + ...esBody, }, { signal: abortSignal, maxRetries: 0 } ); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.test.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.test.ts index 39fd8f5a2bc6a..f3dd3c4ae2ea1 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.test.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.ts index a682d0a5eedb9..1f5fe837e013b 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_index_info.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { AiopsLogRateAnalysisSchema } from '../api/schema'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_log_rate_analysis_for_alert.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_log_rate_analysis_for_alert.ts index 3ba57139901f8..0949045de0372 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_log_rate_analysis_for_alert.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_log_rate_analysis_for_alert.ts @@ -9,7 +9,7 @@ import moment from 'moment'; import { queue } from 'async'; import { chunk } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { withSpan } from '@kbn/apm-utils'; import type { ElasticsearchClient } from '@kbn/core/server'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_groups.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_groups.ts index cde3887c2c5d6..a7adb349f2c7c 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_groups.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_groups.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { Logger } from '@kbn/logging'; @@ -64,11 +64,8 @@ export const fetchMiniHistogramsForSignificantGroups = async ( { index: params.index, size: 0, - body: { - query: histogramQuery, - aggs: wrap(histogramAggs), - size: 0, - }, + query: histogramQuery, + aggs: wrap(histogramAggs), }, { signal: abortSignal, maxRetries: 0 } ); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_items.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_items.ts index 1e28d39996ad5..0442b8a265f6a 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_items.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_mini_histograms_for_significant_items.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { Logger } from '@kbn/logging'; @@ -81,12 +81,9 @@ export const fetchMiniHistogramsForSignificantItems = async ( const resp = await esClient.search( { index: params.index, + query: histogramQuery, + aggs: wrap(histogramAggs), size: 0, - body: { - query: histogramQuery, - aggs: wrap(histogramAggs), - size: 0, - }, }, { signal: abortSignal, maxRetries: 0 } ); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts index 4688a6b566712..ffaf80c1ff7ec 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts @@ -6,7 +6,7 @@ */ import { uniqBy } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { Logger } from '@kbn/logging'; @@ -104,7 +104,7 @@ export const getSignificantTermRequest = ( return { ...getRequestBase(params), - body, + ...body, }; }; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_terms_2_categories_counts.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_terms_2_categories_counts.ts index c4bf46b82d3ff..551d23d9da626 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_terms_2_categories_counts.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_terms_2_categories_counts.ts @@ -7,7 +7,7 @@ import { uniq } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import type { Logger } from '@kbn/logging'; @@ -33,7 +33,7 @@ const getTerm2CategoryCountRequest = ( category: Category, from: number | undefined, to: number | undefined -): estypes.SearchRequest['body'] => { +): estypes.SearchRequest => { const query = getQueryWithParams({ params, }); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts index 803822b7d3940..27538128df51b 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts @@ -6,7 +6,7 @@ */ import { uniqBy } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { type SignificantItem, SIGNIFICANT_ITEM_TYPE } from '@kbn/ml-agg-utils'; import { @@ -79,7 +79,7 @@ export const getTopTermRequest = ( return { ...getRequestBase(params), - body, + ...body, }; }; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_group_filter.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_group_filter.ts index 0b212d66005b2..bfedf95084155 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_group_filter.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_group_filter.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { type SignificantItemGroup, SIGNIFICANT_ITEM_TYPE } from '@kbn/ml-agg-utils'; import { getCategoryQuery } from '@kbn/aiops-log-pattern-analysis/get_category_query'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts index e597e045e0346..3f1d3c0b36cb6 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { AiopsLogRateAnalysisSchema } from '../api/schema'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts index 4a3b425bec863..e63d54df7820f 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FieldValuePair } from '@kbn/ml-agg-utils'; diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_range_query.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_range_query.ts index ca9ae7a299ee7..8d2b415de58bd 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_range_query.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_range_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export function getRangeQuery( start?: number, diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_total_doc_count_request.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_total_doc_count_request.ts index 8314f99478fb4..7ac726b0bcc92 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_total_doc_count_request.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_total_doc_count_request.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { AiopsLogRateAnalysisSchema } from '../api/schema'; @@ -16,11 +16,9 @@ export const getTotalDocCountRequest = ( params: AiopsLogRateAnalysisSchema ): estypes.SearchRequest => ({ ...getRequestBase(params), - body: { - fields: ['*'], - _source: false, - query: getQueryWithParams({ params }), - size: 0, - track_total_hits: true, - }, + fields: ['*'], + _source: false, + query: getQueryWithParams({ params }), + size: 0, + track_total_hits: true, }); diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/mini_histogram_utils.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/mini_histogram_utils.ts index b90e1bd9de416..f23577eebd867 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/mini_histogram_utils.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/mini_histogram_utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { NumericChartData, SignificantItemHistogramItem } from '@kbn/ml-agg-utils'; diff --git a/x-pack/platform/packages/shared/ml/anomaly_utils/es_client.ts b/x-pack/platform/packages/shared/ml/anomaly_utils/es_client.ts index 01f5980613307..1dcb81f3b6910 100644 --- a/x-pack/platform/packages/shared/ml/anomaly_utils/es_client.ts +++ b/x-pack/platform/packages/shared/ml/anomaly_utils/es_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; /** * Alias for QueryDslQueryContainer diff --git a/x-pack/platform/packages/shared/ml/anomaly_utils/fields.ts b/x-pack/platform/packages/shared/ml/anomaly_utils/fields.ts index de39ddeccd477..a1077e83d316e 100644 --- a/x-pack/platform/packages/shared/ml/anomaly_utils/fields.ts +++ b/x-pack/platform/packages/shared/ml/anomaly_utils/fields.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ES_FIELD_TYPES } from '@kbn/field-types'; import type { ML_JOB_AGGREGATION, KIBANA_AGGREGATION, ES_AGGREGATION } from './aggregation_types'; import { MLCATEGORY } from './field_types'; diff --git a/x-pack/platform/packages/shared/ml/error_utils/src/types.ts b/x-pack/platform/packages/shared/ml/error_utils/src/types.ts index 9c247b9352247..961d45d6f6f41 100644 --- a/x-pack/platform/packages/shared/ml/error_utils/src/types.ts +++ b/x-pack/platform/packages/shared/ml/error_utils/src/types.ts @@ -7,7 +7,7 @@ import type Boom from '@hapi/boom'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IHttpFetchError } from '@kbn/core-http-browser'; diff --git a/x-pack/platform/packages/shared/ml/random_sampler_utils/src/random_sampler_wrapper.ts b/x-pack/platform/packages/shared/ml/random_sampler_utils/src/random_sampler_wrapper.ts index 39d26509422a2..243ddec396ce5 100644 --- a/x-pack/platform/packages/shared/ml/random_sampler_utils/src/random_sampler_wrapper.ts +++ b/x-pack/platform/packages/shared/ml/random_sampler_utils/src/random_sampler_wrapper.ts @@ -6,7 +6,7 @@ */ import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { getSampleProbability } from './get_sample_probability'; diff --git a/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_field.ts b/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_field.ts index e04da6a14e99e..f6c7ffdc957b6 100644 --- a/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_field.ts +++ b/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_field.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RUNTIME_FIELD_TYPES } from '@kbn/data-plugin/common'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_mappings.ts b/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_mappings.ts index a77ba88346a71..1344151f3ae1e 100644 --- a/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_mappings.ts +++ b/x-pack/platform/packages/shared/ml/runtime_field_utils/src/is_runtime_mappings.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { isRuntimeField } from './is_runtime_field'; diff --git a/x-pack/platform/packages/shared/ml/trained_models_utils/src/constants/trained_models.ts b/x-pack/platform/packages/shared/ml/trained_models_utils/src/constants/trained_models.ts index 1e5073d803093..e6f1732118342 100644 --- a/x-pack/platform/packages/shared/ml/trained_models_utils/src/constants/trained_models.ts +++ b/x-pack/platform/packages/shared/ml/trained_models_utils/src/constants/trained_models.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; export const ELSER_MODEL_ID = '.elser_model_2'; diff --git a/x-pack/platform/plugins/private/canvas/server/collectors/custom_element_collector.ts b/x-pack/platform/plugins/private/canvas/server/collectors/custom_element_collector.ts index 51aa616f4e5a7..c494d413471ae 100644 --- a/x-pack/platform/plugins/private/canvas/server/collectors/custom_element_collector.ts +++ b/x-pack/platform/plugins/private/canvas/server/collectors/custom_element_collector.ts @@ -150,7 +150,7 @@ const customElementCollector: TelemetryCollector = async function customElementC index, ignore_unavailable: true, filter_path: [`hits.hits._source.${CUSTOM_ELEMENT_TYPE}.content`], - body: { query: { bool: { filter: { term: { type: CUSTOM_ELEMENT_TYPE } } } } }, + query: { bool: { filter: { term: { type: CUSTOM_ELEMENT_TYPE } } } }, }; const esResponse = await esClient.search(customElementParams); diff --git a/x-pack/platform/plugins/private/canvas/server/collectors/workpad_collector.ts b/x-pack/platform/plugins/private/canvas/server/collectors/workpad_collector.ts index 252d05bfc4f7e..5c1d6d9fd7077 100644 --- a/x-pack/platform/plugins/private/canvas/server/collectors/workpad_collector.ts +++ b/x-pack/platform/plugins/private/canvas/server/collectors/workpad_collector.ts @@ -384,7 +384,7 @@ const workpadCollector: TelemetryCollector = async function (getIndexForType, es index, ignore_unavailable: true, filter_path: ['hits.hits._source.canvas-workpad', '-hits.hits._source.canvas-workpad.assets'], - body: { query: { bool: { filter: { term: { type: CANVAS_TYPE } } } } }, + query: { bool: { filter: { term: { type: CANVAS_TYPE } } } }, }; const esResponse = await esClient.search(searchParams); diff --git a/x-pack/platform/plugins/private/canvas/types/strategy.ts b/x-pack/platform/plugins/private/canvas/types/strategy.ts index e3191e03e50f8..1940464153282 100644 --- a/x-pack/platform/plugins/private/canvas/types/strategy.ts +++ b/x-pack/platform/plugins/private/canvas/types/strategy.ts @@ -6,7 +6,7 @@ */ import { TransportResult } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { IKibanaSearchRequest } from '@kbn/search-types'; import { ExpressionValueFilter } from '.'; export interface EssqlSearchStrategyRequest extends IKibanaSearchRequest { diff --git a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts index 40f08389fef63..ad6f4baddfc1f 100644 --- a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts +++ b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts @@ -64,7 +64,7 @@ export const registerCreateRoute = ({ try { const responseBody = await client.asCurrentUser.ccr.putAutoFollowPattern({ name: id, - body, + ...body, }); return response.ok({ diff --git a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts index b7cd60b61d67d..58718ca6207d6 100644 --- a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts +++ b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts @@ -52,11 +52,9 @@ describe('[CCR API] Update auto-follow pattern', () => { expect(response.payload).toEqual({ name: 'foo', - body: { - remote_cluster: 'bar1', - leader_index_patterns: ['bar2'], - follow_index_pattern: 'bar3', - }, + remote_cluster: 'bar1', + leader_index_patterns: ['bar2'], + follow_index_pattern: 'bar3', }); }); }); diff --git a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts index 3fbd2902ef831..13eca5fc2a64f 100644 --- a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts +++ b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts @@ -52,7 +52,7 @@ export const registerUpdateRoute = ({ try { const responseBody = await client.asCurrentUser.ccr.putAutoFollowPattern({ name: id, - body, + ...body, }); return response.ok({ diff --git a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts index 4b59f7eb1b9d3..9f4ff02805e11 100644 --- a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts +++ b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts @@ -44,9 +44,7 @@ export const registerPermissionsRoute = ({ try { const { has_all_requested: hasPermission, cluster } = await client.asCurrentUser.security.hasPrivileges({ - body: { - cluster: ['manage', 'manage_ccr'], - }, + cluster: ['manage', 'manage_ccr'], }); const missingClusterPrivileges = Object.keys(cluster).reduce( diff --git a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts index 75a930da608d5..1a9c87075500f 100644 --- a/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts +++ b/x-pack/platform/plugins/private/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts @@ -6,6 +6,7 @@ */ import { schema } from '@kbn/config-schema'; +import type { CcrFollowRequest } from '@elastic/elasticsearch/lib/api/types'; import { serializeFollowerIndex } from '../../../../common/services/follower_index_serialization'; import { FollowerIndex } from '../../../../common/types'; import { addBasePath } from '../../../services'; @@ -56,9 +57,9 @@ export const registerCreateRoute = ({ try { const responseBody = await client.asCurrentUser.ccr.follow({ + ...body, index: name, - body, - }); + } as CcrFollowRequest); return response.ok({ body: responseBody, diff --git a/x-pack/platform/plugins/private/data_visualizer/common/types/field_stats.ts b/x-pack/platform/plugins/private/data_visualizer/common/types/field_stats.ts index fba26df5cde40..83dfa91511234 100644 --- a/x-pack/platform/plugins/private/data_visualizer/common/types/field_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/common/types/field_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Query } from '@kbn/es-query'; import type { IKibanaSearchResponse } from '@kbn/search-types'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/plugins/private/data_visualizer/common/types/indices.ts b/x-pack/platform/plugins/private/data_visualizer/common/types/indices.ts index dd4bea8602720..de6aa2246d388 100644 --- a/x-pack/platform/plugins/private/data_visualizer/common/types/indices.ts +++ b/x-pack/platform/plugins/private/data_visualizer/common/types/indices.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface IndicesOptions { allow_no_indices?: boolean; diff --git a/x-pack/platform/plugins/private/data_visualizer/common/utils/build_query_filters.ts b/x-pack/platform/plugins/private/data_visualizer/common/utils/build_query_filters.ts index 7fb2e35346484..089217c9c889e 100644 --- a/x-pack/platform/plugins/private/data_visualizer/common/utils/build_query_filters.ts +++ b/x-pack/platform/plugins/private/data_visualizer/common/utils/build_query_filters.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Query } from '@kbn/es-query'; import { buildBaseFilterCriteria } from '@kbn/ml-query-utils'; diff --git a/x-pack/platform/plugins/private/data_visualizer/common/utils/datafeed_utils.ts b/x-pack/platform/plugins/private/data_visualizer/common/utils/datafeed_utils.ts index 5a87d7b01db46..19ba0fa24e296 100644 --- a/x-pack/platform/plugins/private/data_visualizer/common/utils/datafeed_utils.ts +++ b/x-pack/platform/plugins/private/data_visualizer/common/utils/datafeed_utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type Datafeed = estypes.MlDatafeed; export type Aggregation = Record; diff --git a/x-pack/platform/plugins/private/data_visualizer/common/utils/runtime_field_utils.ts b/x-pack/platform/plugins/private/data_visualizer/common/utils/runtime_field_utils.ts index c360f9bb45d50..427a255fb2c09 100644 --- a/x-pack/platform/plugins/private/data_visualizer/common/utils/runtime_field_utils.ts +++ b/x-pack/platform/plugins/private/data_visualizer/common/utils/runtime_field_utils.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RUNTIME_FIELD_TYPES } from '@kbn/data-plugin/common'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/combined_fields_form.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/combined_fields_form.tsx index 7bf8d7f0aaaf3..2cef34ae0da63 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/combined_fields_form.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/combined_fields_form.tsx @@ -20,7 +20,7 @@ import { } from '@elastic/eui'; import type { FindFileStructureResponse, IngestPipeline } from '@kbn/file-upload-plugin/common'; -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import type { CombinedField } from './types'; import { GeoPointForm } from './geo_point'; import { SemanticTextForm } from './semantic_text'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/semantic_text.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/semantic_text.tsx index c1f56214e2ce1..b3b20b2c9f3a8 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/semantic_text.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/semantic_text.tsx @@ -27,7 +27,7 @@ import useDebounce from 'react-use/lib/useDebounce'; import type { InferenceInferenceEndpointInfo, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { createSemanticTextCombinedField, getFieldNames, getNameCollisionMsg } from './utils'; import { useDataVisualizerKibana } from '../../../kibana_context'; import type { AddCombinedField } from './combined_fields_form'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/utils.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/utils.ts index 4b0f57d1ca932..812e6baea7f07 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/utils.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/components/combined_fields/utils.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { cloneDeep } from 'lodash'; import { v4 as uuidv4 } from 'uuid'; -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import type { FindFileStructureResponse, IngestPipeline } from '@kbn/file-upload-plugin/common'; import type { CombinedField } from './types'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_document_count_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_document_count_stats.ts index f345c85f57a42..f4334119762de 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_document_count_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/common/hooks/use_document_count_stats.ts @@ -9,7 +9,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { stringHash } from '@kbn/ml-string-hash'; import { extractErrorProperties } from '@kbn/ml-error-utils'; import type { Query } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SignificantItem } from '@kbn/ml-agg-utils'; import type { RandomSampler, RandomSamplerWrapper } from '@kbn/ml-random-sampler-utils'; import { createRandomSamplerWrapper } from '@kbn/ml-random-sampler-utils'; @@ -111,7 +111,7 @@ export const getDocumentCountStatsRequest = ( }; return { index, - body: searchBody, + ...searchBody, }; }; @@ -122,7 +122,7 @@ export const processDocumentCountStats = ( ): DocumentCountStats | undefined => { if (!body) return undefined; - const totalCount = (body.hits.total as estypes.SearchTotalHits).value ?? body.hits.total ?? 0; + const totalCount = (body.hits.total as estypes.SearchTotalHits)?.value ?? body.hits.total ?? 0; if ( params.intervalMs === undefined || diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx index 745d59e9933a1..02d4b73c774a3 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useCallback, useEffect, useState, useMemo, useRef } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiFlexGroup, EuiFlexItem, diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/types.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/types.ts index 0e1f5ba1b3635..8262180006968 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/types.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import type { Filter, Query } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_result.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_result.ts index e8d2a48f56d08..b79eb7ca6016b 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_result.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_data_drift_result.ts @@ -10,11 +10,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { lastValueFrom } from 'rxjs'; import { getEsQueryConfig } from '@kbn/data-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { - MappingRuntimeFields, - QueryDslBoolQuery, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; +import type { MappingRuntimeFields, QueryDslBoolQuery } from '@elastic/elasticsearch/lib/api/types'; import type { AggregationsAggregate } from '@elastic/elasticsearch/lib/api/types'; import type { IKibanaSearchRequest } from '@kbn/search-types'; @@ -282,7 +279,7 @@ const getDataComparisonQuery = ({ searchQuery?: estypes.QueryDslQueryContainer; datetimeField?: string; timeRange?: TimeRange; -}): NonNullable => { +}): NonNullable => { let rangeFilter; if (timeRange && datetimeField !== undefined && isPopulatedObject(timeRange, ['start', 'end'])) { rangeFilter = { @@ -310,7 +307,7 @@ const getDataComparisonQuery = ({ } } - const queryAndRuntimeMappings: NonNullable = { + const queryAndRuntimeMappings: NonNullable = { query, }; if (runtimeFields) { @@ -365,7 +362,7 @@ const fetchReferenceBaselineData = async ({ const baselineResponse = await dataSearch( { ...baselineRequest, - body: { ...baselineRequest.body, aggs: randomSamplerWrapper.wrap(baselineRequestAggs) }, + aggs: randomSamplerWrapper.wrap(baselineRequestAggs), }, signal ); @@ -452,7 +449,7 @@ const fetchComparisonDriftedData = async ({ const rangesResp = await dataSearch( { ...baselineRequest, - body: { ...baselineRequest.body, aggs: randomSamplerWrapper.wrap(rangesRequestAggs) }, + aggs: randomSamplerWrapper.wrap(rangesRequestAggs), }, signal ); @@ -500,7 +497,7 @@ const fetchComparisonDriftedData = async ({ const driftedResp = await dataSearch( { ...driftedRequest, - body: { ...driftedRequest.body, aggs: randomSamplerWrapper.wrap(driftedRequestAggs) }, + aggs: randomSamplerWrapper.wrap(driftedRequestAggs), }, signal ); @@ -577,10 +574,7 @@ const fetchHistogramData = async ({ if (isPopulatedObject(histogramRequestAggs)) { const histogramRequest = { ...baseRequest, - body: { - ...baseRequest.body, - aggs: randomSamplerWrapper.wrap(histogramRequestAggs), - }, + aggs: randomSamplerWrapper.wrap(histogramRequestAggs), }; return dataSearch(histogramRequest, signal); @@ -786,11 +780,9 @@ export const useFetchDataComparisonResult = ( const baselineRequest: EsRequestParams = { index: referenceIndex, - body: { - size: 0, - aggs: {} as Record, - ...refDataQuery, - }, + size: 0, + aggs: {} as Record, + ...refDataQuery, }; const baselineResponseAggs = await fetchInParallelChunks({ @@ -849,11 +841,9 @@ export const useFetchDataComparisonResult = ( const driftedRequest: EsRequestParams = { index: comparisonIndex, - body: { - size: 0, - aggs: {} as Record, - ...prodDataQuery, - }, + size: 0, + aggs: {} as Record, + ...prodDataQuery, }; const driftedRespAggs = await fetchInParallelChunks({ @@ -892,11 +882,9 @@ export const useFetchDataComparisonResult = ( const referenceHistogramRequest: EsRequestParams = { index: referenceIndex, - body: { - size: 0, - aggs: {} as Record, - ...refDataQuery, - }, + size: 0, + aggs: {} as Record, + ...refDataQuery, }; const referenceHistogramRespAggs = await fetchInParallelChunks({ @@ -937,11 +925,9 @@ export const useFetchDataComparisonResult = ( const comparisonHistogramRequest: EsRequestParams = { index: comparisonIndex, - body: { - size: 0, - aggs: {} as Record, - ...prodDataQuery, - }, + size: 0, + aggs: {} as Record, + ...prodDataQuery, }; const comparisonHistogramRespAggs = await fetchInParallelChunks({ diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_state_manager.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_state_manager.ts index 2c34b9d90c01a..f7196705b2ee9 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_state_manager.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/use_state_manager.ts @@ -8,7 +8,7 @@ import { createContext, useContext, useState } from 'react'; import type { DataView } from '@kbn/data-views-plugin/common'; import type { Filter } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SearchQueryLanguage } from '@kbn/ml-query-utils'; import { RandomSampler } from '@kbn/ml-random-sampler-utils'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/doc_count_search.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/doc_count_search.ts index c48b5f3d23077..795d074c2595d 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/doc_count_search.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/doc_count_chart/doc_count_search.ts @@ -7,7 +7,7 @@ import { lastValueFrom } from 'rxjs'; -import type estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type estypes from '@elastic/elasticsearch/lib/api/types'; import type { IKibanaSearchResponse } from '@kbn/search-types'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { TimeBuckets } from '@kbn/ml-time-buckets'; @@ -38,36 +38,34 @@ export async function runDocCountSearch( dataStart.search.search({ params: { index, - body: { - size: 0, - query: { - bool: { - must: [ - { - range: { - [timeField]: { - gte: earliestMs, - lte: latestMs, - format: 'epoch_millis', - }, + size: 0, + query: { + bool: { + must: [ + { + range: { + [timeField]: { + gte: earliestMs, + lte: latestMs, + format: 'epoch_millis', }, }, - { - match_all: {}, - }, - ], - }, + }, + { + match_all: {}, + }, + ], }, - aggs: { - eventRate: { - date_histogram: { - field: timeField, - fixed_interval: `${intervalMs}ms`, - min_doc_count: 0, - extended_bounds: { - min: earliestMs, - max: latestMs, - }, + }, + aggs: { + eventRate: { + date_histogram: { + field: timeField, + fixed_interval: `${intervalMs}ms`, + min_doc_count: 0, + extended_bounds: { + min: earliestMs, + max: latestMs, }, }, }, diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced/use_existing_indices.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced/use_existing_indices.ts index 19526c799d2aa..6f3c7ef6c55b3 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced/use_existing_indices.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced/use_existing_indices.ts @@ -6,7 +6,7 @@ */ import { useCallback, useState, useEffect } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useDataVisualizerKibana } from '../../../../kibana_context'; interface EsIndex { diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/auto_deploy.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/auto_deploy.ts index 2694be7aa4379..178a2ef613ba8 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/auto_deploy.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/auto_deploy.ts @@ -8,7 +8,7 @@ import type { InferenceInferenceEndpointInfo, InferenceInferenceResponse, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { HttpSetup } from '@kbn/core/public'; const POLL_INTERVAL = 5; // seconds diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/import.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/import.ts index c8fb9458b7c75..7b764caba1dde 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/import.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/file_data_visualizer/components/import_view/import.ts @@ -13,7 +13,7 @@ import type { import type { FileUploadStartApi } from '@kbn/file-upload-plugin/public/api'; import { i18n } from '@kbn/i18n'; import type { HttpSetup } from '@kbn/core/public'; -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { IMPORT_STATUS } from '../import_progress/import_progress'; import { AutoDeploy } from './auto_deploy'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx index 26b8ff3cf24d7..c68005e22add7 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx @@ -10,7 +10,7 @@ import { merge } from 'rxjs'; import { Comparators } from '@elastic/eui'; import { useUrlState } from '@kbn/ml-url-state'; import { KBN_FIELD_TYPES } from '@kbn/field-types'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { getFieldType } from '@kbn/field-utils'; import { UI_SETTINGS } from '@kbn/data-service'; import useObservable from 'react-use/lib/useObservable'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/use_overall_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/use_overall_stats.ts index 7051038b7803b..c1aff1a1ff909 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/use_overall_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/use_overall_stats.ts @@ -18,7 +18,7 @@ import { extractErrorProperties } from '@kbn/ml-error-utils'; import { getProcessedFields } from '@kbn/ml-data-grid'; import { isDefined } from '@kbn/ml-is-defined'; import type { FieldSpec } from '@kbn/data-views-plugin/common'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import { useDataVisualizerKibana } from '../../kibana_context'; import type { AggregatableFieldOverallStats, diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/esql_requests/get_count_and_cardinality.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/esql_requests/get_count_and_cardinality.ts index e1f6b45b37e00..81c9fb74c78e6 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/esql_requests/get_count_and_cardinality.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/esql_requests/get_count_and_cardinality.ts @@ -12,7 +12,7 @@ import type { TimeRange } from '@kbn/es-query'; import type { ESQLSearchResponse } from '@kbn/es-types'; import { appendToESQLQuery, getStartEndParams } from '@kbn/esql-utils'; import type { UseCancellableSearch } from '@kbn/ml-cancellable-search'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { getSafeESQLName } from '../requests/esql_utils'; import { MAX_CONCURRENT_REQUESTS } from '../../constants/index_data_visualizer_viewer'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/build_random_sampler_agg.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/build_random_sampler_agg.ts index b901d84e94e07..2b052d4e6f24f 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/build_random_sampler_agg.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/build_random_sampler_agg.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Aggs, SamplingOption } from '../../../../../common/types/field_stats'; import { isNormalSamplingOption, diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_boolean_field_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_boolean_field_stats.ts index a283b8ff47bb7..c6697d876960f 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_boolean_field_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_boolean_field_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Observable } from 'rxjs'; import { of } from 'rxjs'; import { catchError, map } from 'rxjs'; @@ -58,7 +58,7 @@ export const getBooleanFieldsStatsRequest = ( return { index, size, - body: searchBody, + ...searchBody, }; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_date_field_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_date_field_stats.ts index 93431c0334101..da61c584642c3 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_date_field_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_date_field_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { get } from 'lodash'; import type { Observable } from 'rxjs'; import { of } from 'rxjs'; @@ -55,7 +55,7 @@ export const getDateFieldsStatsRequest = ( return { index, size, - body: searchBody, + ...searchBody, }; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_document_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_document_stats.ts index 72ae034c8b5ad..8313a066f00c0 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_document_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_document_stats.ts @@ -6,7 +6,7 @@ */ import { each, get, sortedIndex } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import type { ISearchOptions } from '@kbn/search-types'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; @@ -91,11 +91,9 @@ export const getDocumentCountStats = async ( const getSearchParams = (aggregations: unknown, trackTotalHits = false) => ({ index, - body: { - query, - ...(hasTimeField ? { aggs: aggregations } : {}), - ...(isPopulatedObject(runtimeFieldMap) ? { runtime_mappings: runtimeFieldMap } : {}), - }, + query, + ...(hasTimeField ? { aggs: aggregations } : {}), + ...(isPopulatedObject(runtimeFieldMap) ? { runtime_mappings: runtimeFieldMap } : {}), track_total_hits: trackTotalHits, size: 0, }); diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_field_examples.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_field_examples.ts index 4ae2841b56ded..2093b82ff5087 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_field_examples.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_field_examples.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { get } from 'lodash'; import { combineLatest, of } from 'rxjs'; import { catchError, map } from 'rxjs'; @@ -15,7 +15,7 @@ import type { } from '@kbn/search-types'; import type { ISearchStart } from '@kbn/data-plugin/public'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; -import type { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { extractErrorProperties } from '@kbn/ml-error-utils'; import { getUniqGeoOrStrExamples } from '../../../common/util/example_utils'; import type { @@ -58,7 +58,7 @@ export const getFieldExamplesRequest = (params: FieldStatsCommonRequestParams, f return { index, size, - body: searchBody, + ...searchBody, }; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_numeric_field_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_numeric_field_stats.ts index 41569286d47b5..4203900307ef3 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_numeric_field_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_numeric_field_stats.ts @@ -5,12 +5,12 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { find, get } from 'lodash'; import { catchError, map } from 'rxjs'; import type { Observable } from 'rxjs'; import { of } from 'rxjs'; -import type { AggregationsTermsAggregation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsTermsAggregation } from '@elastic/elasticsearch/lib/api/types'; import type { IKibanaSearchResponse, IKibanaSearchRequest, @@ -122,7 +122,7 @@ export const getNumericFieldsStatsRequest = ( return { index, size, - body: searchBody, + ...searchBody, }; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_string_field_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_string_field_stats.ts index 6e323f63a37a3..b82ddeb80b89a 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_string_field_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/get_string_field_stats.ts @@ -4,12 +4,12 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { get } from 'lodash'; import type { Observable } from 'rxjs'; import { of } from 'rxjs'; import { catchError, map } from 'rxjs'; -import type { AggregationsTermsAggregation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsTermsAggregation } from '@elastic/elasticsearch/lib/api/types'; import type { IKibanaSearchResponse, IKibanaSearchRequest, @@ -62,7 +62,7 @@ export const getStringFieldStatsRequest = ( return { index, size, - body: searchBody, + ...searchBody, }; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/overall_stats.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/overall_stats.ts index cd764d5ba4ede..38ae06a8038b9 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/overall_stats.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/search_strategy/requests/overall_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { get } from 'lodash'; import type { Query } from '@kbn/es-query'; import type { IKibanaSearchResponse } from '@kbn/search-types'; @@ -90,10 +90,9 @@ export const checkAggregatableFieldsExistRequest = ( return { index, - // @ts-expect-error `track_total_hits` not allowed at top level for `typesWithBodyKey` track_total_hits: false, size, - body: searchBody, + ...searchBody, }; }; @@ -241,9 +240,8 @@ export const checkNonAggregatableFieldExistsRequest = ( return { index, - // @ts-expect-error `size` not allowed at top level for `typesWithBodyKey` size, - body: searchBody, + ...searchBody, // Small es optimization // Since we only need to know if at least 1 doc exists for the query track_total_hits: 1, @@ -270,17 +268,15 @@ export const getSampleOfDocumentsForNonAggregatableFields = ( return { index, - body: { - fields: nonAggregatableFields.map((fieldName) => fieldName), - _source: false, - query: { - bool: { - filter: filterCriteria, - }, + fields: nonAggregatableFields.map((fieldName) => fieldName), + _source: false, + query: { + bool: { + filter: filterCriteria, }, - ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), - size: DEFAULT_DOCS_SAMPLE_OF_TEXT_FIELDS_SIZE, }, + ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), + size: DEFAULT_DOCS_SAMPLE_OF_TEXT_FIELDS_SIZE, }; }; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts index 7a2292a08bbaf..6d0f8970187a9 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts @@ -11,7 +11,7 @@ import { cloneDeep } from 'lodash'; import type { IUiSettingsClient } from '@kbn/core/public'; import type { Query, Filter, AggregateQuery } from '@kbn/es-query'; import { buildEsQuery } from '@kbn/es-query'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { DataView } from '@kbn/data-views-plugin/public'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import { getEsQueryConfig, SearchSource } from '@kbn/data-plugin/common'; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/lite/file_manager/file_manager.ts b/x-pack/platform/plugins/private/data_visualizer/public/lite/file_manager/file_manager.ts index 0eccd4ad2d72f..08ae654931167 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/lite/file_manager/file_manager.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/lite/file_manager/file_manager.ts @@ -17,7 +17,7 @@ import type { ImportResponse, IngestPipeline } from '@kbn/file-upload-plugin/com import type { IndicesIndexSettings, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import type { FileUploadResults } from '@kbn/file-upload-common'; import type { FileAnalysis } from './file_wrapper'; diff --git a/x-pack/platform/plugins/private/file_upload/common/types.ts b/x-pack/platform/plugins/private/file_upload/common/types.ts index 409b5fcac80a1..b984213749c0c 100644 --- a/x-pack/platform/plugins/private/file_upload/common/types.ts +++ b/x-pack/platform/plugins/private/file_upload/common/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ES_FIELD_TYPES } from '@kbn/data-plugin/common'; export interface InputOverrides { diff --git a/x-pack/platform/plugins/private/file_upload/public/importer/importer.ts b/x-pack/platform/plugins/private/file_upload/public/importer/importer.ts index bbb6f86d56be8..56ac68166fe49 100644 --- a/x-pack/platform/plugins/private/file_upload/public/importer/importer.ts +++ b/x-pack/platform/plugins/private/file_upload/public/importer/importer.ts @@ -11,7 +11,7 @@ import type { IndicesIndexSettings, IngestDeletePipelineResponse, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { getHttp } from '../kibana_services'; diff --git a/x-pack/platform/plugins/private/file_upload/public/importer/types.ts b/x-pack/platform/plugins/private/file_upload/public/importer/types.ts index 1694b1b2d5de1..e15d6cbb03931 100644 --- a/x-pack/platform/plugins/private/file_upload/public/importer/types.ts +++ b/x-pack/platform/plugins/private/file_upload/public/importer/types.ts @@ -9,7 +9,7 @@ import type { IndicesIndexSettings, IngestDeletePipelineResponse, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { ImportFailure, IngestPipeline, ImportDoc, ImportResponse } from '../../common/types'; diff --git a/x-pack/platform/plugins/private/file_upload/server/get_time_field_range.ts b/x-pack/platform/plugins/private/file_upload/server/get_time_field_range.ts index 32bf1766f8d90..9b85fea50ec7f 100644 --- a/x-pack/platform/plugins/private/file_upload/server/get_time_field_range.ts +++ b/x-pack/platform/plugins/private/file_upload/server/get_time_field_range.ts @@ -5,7 +5,7 @@ * 2.0. */ import { IScopedClusterClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; @@ -25,22 +25,20 @@ export async function getTimeFieldRange( const { aggregations } = await client.asCurrentUser.search({ index, size: 0, - body: { - ...(query ? { query } : {}), - aggs: { - earliest: { - min: { - field: timeFieldName, - }, + ...(query ? { query } : {}), + aggs: { + earliest: { + min: { + field: timeFieldName, }, - latest: { - max: { - field: timeFieldName, - }, + }, + latest: { + max: { + field: timeFieldName, }, }, - ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), }, + ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), }); if (aggregations && aggregations.earliest && aggregations.latest) { diff --git a/x-pack/platform/plugins/private/file_upload/server/import_data.ts b/x-pack/platform/plugins/private/file_upload/server/import_data.ts index 605adecb376da..98eb182dd2351 100644 --- a/x-pack/platform/plugins/private/file_upload/server/import_data.ts +++ b/x-pack/platform/plugins/private/file_upload/server/import_data.ts @@ -11,7 +11,7 @@ import type { IndicesCreateRequest, IndicesIndexSettings, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { INDEX_META_DATA_CREATED_BY } from '../common/constants'; import { ImportResponse, ImportFailure, InputData, IngestPipelineWrapper } from '../common/types'; @@ -102,7 +102,7 @@ export function importDataProvider({ asCurrentUser }: IScopedClusterClient) { settings: IndicesIndexSettings, mappings: MappingTypeMapping ) { - const body: IndicesCreateRequest['body'] = { + const body: Omit = { mappings: { _meta: { created_by: INDEX_META_DATA_CREATED_BY, @@ -115,7 +115,7 @@ export function importDataProvider({ asCurrentUser }: IScopedClusterClient) { body.settings = settings; } - await asCurrentUser.indices.create({ index, body }, { maxRetries: 0 }); + await asCurrentUser.indices.create({ index, ...body }, { maxRetries: 0 }); } async function indexData(index: string, pipelineId: string | undefined, data: InputData) { diff --git a/x-pack/platform/plugins/private/file_upload/server/preview_index_time_range.ts b/x-pack/platform/plugins/private/file_upload/server/preview_index_time_range.ts index ae1e8deaeac04..36f29f13dd08c 100644 --- a/x-pack/platform/plugins/private/file_upload/server/preview_index_time_range.ts +++ b/x-pack/platform/plugins/private/file_upload/server/preview_index_time_range.ts @@ -8,11 +8,11 @@ import dateMath from '@kbn/datemath'; import type { IngestPipeline, - IngestSimulateDocument, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; + IngestDocumentSimulation, +} from '@elastic/elasticsearch/lib/api/types'; import type { IScopedClusterClient } from '@kbn/core/server'; -type Doc = IngestSimulateDocument['_source']; +type Doc = IngestDocumentSimulation['_source']; /** * Returns the start and end time range in epoch milliseconds for a given set of documents diff --git a/x-pack/platform/plugins/private/file_upload/server/routes.ts b/x-pack/platform/plugins/private/file_upload/server/routes.ts index f7ef6e15b0c91..8a368e3c46e94 100644 --- a/x-pack/platform/plugins/private/file_upload/server/routes.ts +++ b/x-pack/platform/plugins/private/file_upload/server/routes.ts @@ -11,7 +11,7 @@ import type { CoreSetup, Logger } from '@kbn/core/server'; import type { IndicesIndexSettings, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { MAX_FILE_SIZE_BYTES, MAX_TIKA_FILE_SIZE_BYTES } from '../common/constants'; import type { IngestPipelineWrapper, InputData } from '../common/types'; import { wrapError } from './error_wrapper'; diff --git a/x-pack/platform/plugins/private/file_upload/server/utils/runtime_field_utils.ts b/x-pack/platform/plugins/private/file_upload/server/utils/runtime_field_utils.ts index ed55eed02c882..6b6f738b6e6e6 100644 --- a/x-pack/platform/plugins/private/file_upload/server/utils/runtime_field_utils.ts +++ b/x-pack/platform/plugins/private/file_upload/server/utils/runtime_field_utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RUNTIME_FIELD_TYPES } from '@kbn/data-plugin/common'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/plugins/private/graph/public/helpers/use_graph_loader.ts b/x-pack/platform/plugins/private/graph/public/helpers/use_graph_loader.ts index 2b0b4b6d839e1..96757dc3fbdab 100644 --- a/x-pack/platform/plugins/private/graph/public/helpers/use_graph_loader.ts +++ b/x-pack/platform/plugins/private/graph/public/helpers/use_graph_loader.ts @@ -9,7 +9,7 @@ import { useCallback, useMemo, useState } from 'react'; import type { CoreStart, ToastsStart } from '@kbn/core/public'; import type { IHttpFetchError, ResponseErrorBody } from '@kbn/core-http-browser'; import { i18n } from '@kbn/i18n'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RequestAdapter } from '@kbn/inspector-plugin/public'; import type { ExploreRequest, diff --git a/x-pack/platform/plugins/private/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts b/x-pack/platform/plugins/private/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts index 0e86beddb7773..0040db90cbfa9 100644 --- a/x-pack/platform/plugins/private/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts +++ b/x-pack/platform/plugins/private/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts @@ -40,9 +40,9 @@ export function registerGrokSimulateRoute(framework: KibanaFramework) { try { const esClient = (await requestContext.core).elasticsearch.client; const grokdebuggerRequest = GrokdebuggerRequest.fromDownstreamJSON(request.body); - const simulateResponseFromES = await esClient.asCurrentUser.ingest.simulate({ - body: grokdebuggerRequest.upstreamJSON, - }); + const simulateResponseFromES = await esClient.asCurrentUser.ingest.simulate( + grokdebuggerRequest.upstreamJSON + ); const grokdebuggerResponse = GrokdebuggerResponse.fromUpstreamJSON(simulateResponseFromES); return response.ok({ body: grokdebuggerResponse, diff --git a/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts b/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts index 7d6039ba0df72..6a4e83168c3ad 100644 --- a/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts +++ b/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts @@ -17,14 +17,14 @@ async function addLifecyclePolicy( policyName: string, alias: string ) { - const body = { + const settings = { lifecycle: { name: policyName, rollover_alias: alias, }, }; - return client.indices.putSettings({ index: indexName, body }); + return client.indices.putSettings({ index: indexName, settings }); } const bodySchema = schema.object({ diff --git a/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/policies/register_create_route.ts b/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/policies/register_create_route.ts index 97370b4a15039..0e2c3fe446064 100644 --- a/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/policies/register_create_route.ts +++ b/x-pack/platform/plugins/private/index_lifecycle_management/server/routes/api/policies/register_create_route.ts @@ -16,12 +16,11 @@ async function createPolicy( name: string, policy: Omit ): Promise { - const body = { policy }; const options = { ignore: [404], }; - return client.ilm.putLifecycle({ name, body }, options); + return client.ilm.putLifecycle({ name, policy }, options); } /** diff --git a/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.test.ts b/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.test.ts index 34f750ac776a2..8a55ebc73f1a8 100755 --- a/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.test.ts +++ b/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { Cluster } from './cluster'; describe('cluster', () => { diff --git a/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.ts b/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.ts index c3a3729254623..449da28aca40f 100755 --- a/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.ts +++ b/x-pack/platform/plugins/private/logstash/server/models/cluster/cluster.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; /** * This model deals with a cluster object from ES and converts it to Kibana downstream diff --git a/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts b/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts index fbb4daba34532..47bc3636d21a8 100644 --- a/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts +++ b/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts @@ -7,7 +7,7 @@ import { ElasticsearchClient } from '@kbn/core/server'; import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { StackProductUsage } from '../types'; interface ESIndicesBucket { diff --git a/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts b/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts index 4d30e4f0b021b..0c45575062521 100644 --- a/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts +++ b/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { INDEX_PATTERN_ELASTICSEARCH } from '../../../../common/constants'; import { getCcsIndexPattern } from '../../../lib/alerts/get_ccs_index_pattern'; diff --git a/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts b/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts index bfce72d885a0b..de8e3edec5e41 100644 --- a/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts +++ b/x-pack/platform/plugins/private/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { MonitoringConfig } from '../../../config'; import { StackProductUsage } from '../types'; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_available_ccs.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_available_ccs.test.ts index dfedc24122917..013d4230bcd70 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_available_ccs.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_available_ccs.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { fetchAvailableCcs } from './fetch_available_ccs'; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.test.ts index 8fdfc76c4d061..54b21e65f6a03 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.test.ts @@ -42,82 +42,80 @@ describe('fetchCCReadExceptions', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.ccr-*,metrics-elasticsearch.stack_monitoring.ccr-*', filter_path: ['aggregations.remote_clusters.buckets'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - bool: { - should: [ - { - nested: { - ignore_unmapped: true, - path: 'ccr_stats.read_exceptions', - query: { - exists: { - field: 'ccr_stats.read_exceptions.exception', - }, + size: 0, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { + nested: { + ignore_unmapped: true, + path: 'ccr_stats.read_exceptions', + query: { + exists: { + field: 'ccr_stats.read_exceptions.exception', }, }, }, - { - nested: { - ignore_unmapped: true, - path: 'elasticsearch.ccr.read_exceptions', - query: { - exists: { - field: 'elasticsearch.ccr.read_exceptions.exception', - }, + }, + { + nested: { + ignore_unmapped: true, + path: 'elasticsearch.ccr.read_exceptions', + query: { + exists: { + field: 'elasticsearch.ccr.read_exceptions.exception', }, }, }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - { - bool: { - should: [ - { term: { type: 'ccr_stats' } }, - { term: { 'metricset.name': 'ccr' } }, - { term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.ccr' } }, - ], - minimum_should_match: 1, - }, + }, + { + bool: { + should: [ + { term: { type: 'ccr_stats' } }, + { term: { 'metricset.name': 'ccr' } }, + { term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.ccr' } }, + ], + minimum_should_match: 1, }, - { - range: { - timestamp: { format: 'epoch_millis', gte: 1643306331418, lte: 1643309869056 }, - }, + }, + { + range: { + timestamp: { format: 'epoch_millis', gte: 1643306331418, lte: 1643309869056 }, }, - ], - }, + }, + ], }, - aggs: { - remote_clusters: { - terms: { field: 'ccr_stats.remote_cluster', size: 10000 }, - aggs: { - follower_indices: { - terms: { field: 'ccr_stats.follower_index', size: 10000 }, - aggs: { - hits: { - top_hits: { - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - _source: { - includes: [ - 'cluster_uuid', - 'elasticsearch.cluster.id', - 'ccr_stats.read_exceptions', - 'elasticsearch.ccr.read_exceptions', - 'ccr_stats.shard_id', - 'elasticsearch.ccr.shard_id', - 'ccr_stats.leader_index', - 'elasticsearch.ccr.leader.index', - ], - }, - size: 1, + }, + aggs: { + remote_clusters: { + terms: { field: 'ccr_stats.remote_cluster', size: 10000 }, + aggs: { + follower_indices: { + terms: { field: 'ccr_stats.follower_index', size: 10000 }, + aggs: { + hits: { + top_hits: { + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + _source: { + includes: [ + 'cluster_uuid', + 'elasticsearch.cluster.id', + 'ccr_stats.read_exceptions', + 'elasticsearch.ccr.read_exceptions', + 'ccr_stats.shard_id', + 'elasticsearch.ccr.shard_id', + 'ccr_stats.leader_index', + 'elasticsearch.ccr.leader.index', + ], }, + size: 1, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.ts index 50cc76225f418..2cb7f3d26706c 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_ccr_read_exceptions.ts @@ -30,90 +30,88 @@ export async function fetchCCRReadExceptions( const params = { index: indexPatterns, filter_path: ['aggregations.remote_clusters.buckets'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - bool: { - should: [ - { - nested: { - ignore_unmapped: true, - path: 'ccr_stats.read_exceptions', - query: { - exists: { - field: 'ccr_stats.read_exceptions.exception', - }, + size: 0, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { + nested: { + ignore_unmapped: true, + path: 'ccr_stats.read_exceptions', + query: { + exists: { + field: 'ccr_stats.read_exceptions.exception', }, }, }, - { - nested: { - ignore_unmapped: true, - path: 'elasticsearch.ccr.read_exceptions', - query: { - exists: { - field: 'elasticsearch.ccr.read_exceptions.exception', - }, + }, + { + nested: { + ignore_unmapped: true, + path: 'elasticsearch.ccr.read_exceptions', + query: { + exists: { + field: 'elasticsearch.ccr.read_exceptions.exception', }, }, }, - ], - minimum_should_match: 1, - }, - }, - createDatasetFilter('ccr_stats', 'ccr', getElasticsearchDataset('ccr')), - { - range: { - timestamp: { - format: 'epoch_millis', - gte: startMs, - lte: endMs, }, - }, + ], + minimum_should_match: 1, }, - ], - }, - }, - aggs: { - remote_clusters: { - terms: { - field: 'ccr_stats.remote_cluster', - size, }, - aggs: { - follower_indices: { - terms: { - field: 'ccr_stats.follower_index', - size, + createDatasetFilter('ccr_stats', 'ccr', getElasticsearchDataset('ccr')), + { + range: { + timestamp: { + format: 'epoch_millis', + gte: startMs, + lte: endMs, }, - aggs: { - hits: { - top_hits: { - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + }, + }, + ], + }, + }, + aggs: { + remote_clusters: { + terms: { + field: 'ccr_stats.remote_cluster', + size, + }, + aggs: { + follower_indices: { + terms: { + field: 'ccr_stats.follower_index', + size, + }, + aggs: { + hits: { + top_hits: { + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - _source: { - includes: [ - 'cluster_uuid', - 'elasticsearch.cluster.id', - 'ccr_stats.read_exceptions', - 'elasticsearch.ccr.read_exceptions', - 'ccr_stats.shard_id', - 'elasticsearch.ccr.shard_id', - 'ccr_stats.leader_index', - 'elasticsearch.ccr.leader.index', - ], }, - size: 1, + ], + _source: { + includes: [ + 'cluster_uuid', + 'elasticsearch.cluster.id', + 'ccr_stats.read_exceptions', + 'elasticsearch.ccr.read_exceptions', + 'ccr_stats.shard_id', + 'elasticsearch.ccr.shard_id', + 'ccr_stats.leader_index', + 'elasticsearch.ccr.leader.index', + ], }, + size: 1, }, }, }, @@ -126,7 +124,7 @@ export async function fetchCCRReadExceptions( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.test.ts index fa61cfa3e00f5..f13d7f37b5859 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { fetchClusterHealth } from './fetch_cluster_health'; @@ -74,33 +74,31 @@ describe('fetchClusterHealth', () => { 'hits.hits._source.elasticsearch.cluster.id', 'hits.hits._index', ], - body: { - size: 2, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['1', '2'] } }, - { - bool: { - should: [ - { term: { type: 'cluster_stats' } }, - { term: { 'metricset.name': 'cluster_stats' } }, - { - term: { - 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', - }, + size: 2, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['1', '2'] } }, + { + bool: { + should: [ + { term: { type: 'cluster_stats' } }, + { term: { 'metricset.name': 'cluster_stats' } }, + { + term: { + 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-1h' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-1h' } } }, + ], }, - collapse: { field: 'cluster_uuid' }, }, + collapse: { field: 'cluster_uuid' }, }); }); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.ts index 1d35440d65ae3..3f6a8df04fa5b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cluster_health.ts @@ -34,49 +34,47 @@ export async function fetchClusterHealth( 'hits.hits._source.elasticsearch.cluster.id', 'hits.hits._index', ], - body: { - size: clusters.length, - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + size: clusters.length, + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + }, + ], + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter( - 'cluster_stats', - 'cluster_stats', - getElasticsearchDataset('cluster_stats') - ), - { - range: { - timestamp: { - gte: `now-${duration}`, - }, + }, + createDatasetFilter( + 'cluster_stats', + 'cluster_stats', + getElasticsearchDataset('cluster_stats') + ), + { + range: { + timestamp: { + gte: `now-${duration}`, }, }, - ], - }, - }, - collapse: { - field: 'cluster_uuid', + }, + ], }, }, + collapse: { + field: 'cluster_uuid', + }, }; try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.test.ts index b2366fbccb424..3d62185345b42 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { fetchClusters } from './fetch_clusters'; @@ -75,7 +75,7 @@ describe('fetchClusters', () => { const esClient = elasticsearchServiceMock.createScopedClusterClient().asCurrentUser; await fetchClusters(esClient); const params = esClient.search.mock.calls[0][0] as any; - expect(params?.body?.query.bool.filter[1].range.timestamp.gte).toBe('now-2m'); + expect(params?.query.bool.filter[1].range.timestamp.gte).toBe('now-2m'); }); it('should call ES with correct query', async () => { @@ -91,31 +91,29 @@ describe('fetchClusters', () => { 'hits.hits._source.cluster_name', 'hits.hits._source.elasticsearch.cluster.name', ], - body: { - size: 1000, - query: { - bool: { - filter: [ - { - bool: { - should: [ - { term: { type: 'cluster_stats' } }, - { term: { 'metricset.name': 'cluster_stats' } }, - { - term: { - 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', - }, + size: 1000, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { term: { type: 'cluster_stats' } }, + { term: { 'metricset.name': 'cluster_stats' } }, + { + term: { + 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-2m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-2m' } } }, + ], }, - collapse: { field: 'cluster_uuid' }, }, + collapse: { field: 'cluster_uuid' }, }); }); it('should call ES with correct query when ccs disabled', async () => { diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.ts index 870d1dde9e4ca..5b4d5eaac74ce 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_clusters.ts @@ -39,26 +39,24 @@ export async function fetchClusters( 'hits.hits._source.cluster_name', 'hits.hits._source.elasticsearch.cluster.name', ], - body: { - size: 1000, - query: { - bool: { - filter: [ - createDatasetFilter( - 'cluster_stats', - 'cluster_stats', - getElasticsearchDataset('cluster_stats') - ), - { - range: rangeFilter, - }, - ], - }, - }, - collapse: { - field: 'cluster_uuid', + size: 1000, + query: { + bool: { + filter: [ + createDatasetFilter( + 'cluster_stats', + 'cluster_stats', + getElasticsearchDataset('cluster_stats') + ), + { + range: rangeFilter, + }, + ], }, }, + collapse: { + field: 'cluster_uuid', + }, }; const response = await esClient.search(params); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts index 8981f336ff90c..6df88011a157d 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { fetchCpuUsageNodeStats } from './fetch_cpu_usage_node_stats'; @@ -216,62 +216,60 @@ describe('fetchCpuUsageNodeStats', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.node_stats-*,metrics-elasticsearch.stack_monitoring.node_stats-*', filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['abc123'] } }, - { - bool: { - should: [ - { term: { type: 'node_stats' } }, - { term: { 'metricset.name': 'node_stats' } }, - { - term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, - }, - ], - minimum_should_match: 1, - }, - }, - { range: { timestamp: { format: 'epoch_millis', gte: 0, lte: 0 } } }, - { - bool: { should: [{ exists: { field: 'cluster_uuid' } }], minimum_should_match: 1 }, + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['abc123'] } }, + { + bool: { + should: [ + { term: { type: 'node_stats' } }, + { term: { 'metricset.name': 'node_stats' } }, + { + term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, + }, + ], + minimum_should_match: 1, }, - ], - }, + }, + { range: { timestamp: { format: 'epoch_millis', gte: 0, lte: 0 } } }, + { + bool: { should: [{ exists: { field: 'cluster_uuid' } }], minimum_should_match: 1 }, + }, + ], }, - aggs: { - clusters: { - terms: { field: 'cluster_uuid', size: 10, include: ['abc123'] }, - aggs: { - nodes: { - terms: { field: 'node_stats.node_id', size: 10 }, - aggs: { - index: { terms: { field: '_index', size: 1 } }, - average_cpu: { avg: { field: 'node_stats.process.cpu.percent' } }, - average_quota: { avg: { field: 'node_stats.os.cgroup.cpu.cfs_quota_micros' } }, - name: { terms: { field: 'source_node.name', size: 1 } }, - histo: { - date_histogram: { field: 'timestamp', fixed_interval: '0m' }, - aggs: { - average_periods: { - max: { field: 'node_stats.os.cgroup.cpu.stat.number_of_elapsed_periods' }, - }, - average_usage: { max: { field: 'node_stats.os.cgroup.cpuacct.usage_nanos' } }, - usage_deriv: { - derivative: { - buckets_path: 'average_usage', - gap_policy: 'skip', - unit: '1s', - }, + }, + aggs: { + clusters: { + terms: { field: 'cluster_uuid', size: 10, include: ['abc123'] }, + aggs: { + nodes: { + terms: { field: 'node_stats.node_id', size: 10 }, + aggs: { + index: { terms: { field: '_index', size: 1 } }, + average_cpu: { avg: { field: 'node_stats.process.cpu.percent' } }, + average_quota: { avg: { field: 'node_stats.os.cgroup.cpu.cfs_quota_micros' } }, + name: { terms: { field: 'source_node.name', size: 1 } }, + histo: { + date_histogram: { field: 'timestamp', fixed_interval: '0m' }, + aggs: { + average_periods: { + max: { field: 'node_stats.os.cgroup.cpu.stat.number_of_elapsed_periods' }, + }, + average_usage: { max: { field: 'node_stats.os.cgroup.cpuacct.usage_nanos' } }, + usage_deriv: { + derivative: { + buckets_path: 'average_usage', + gap_policy: 'skip', + unit: '1s', }, - periods_deriv: { - derivative: { - buckets_path: 'average_periods', - gap_policy: 'skip', - unit: '1s', - }, + }, + periods_deriv: { + derivative: { + buckets_path: 'average_periods', + gap_policy: 'skip', + unit: '1s', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts index 761d3087d8c73..a4d6141e792a9 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts @@ -48,94 +48,92 @@ export async function fetchCpuUsageNodeStats( const params = { index: indexPatterns, filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), - { - range: { - timestamp: { - format: 'epoch_millis', - gte: startMs, - lte: endMs, - }, + }, + createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), + { + range: { + timestamp: { + format: 'epoch_millis', + gte: startMs, + lte: endMs, }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - field: 'cluster_uuid', - size, - include: clusters.map((cluster) => cluster.clusterUuid), }, - aggs: { - nodes: { - terms: { - field: 'node_stats.node_id', - size, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + include: clusters.map((cluster) => cluster.clusterUuid), + }, + aggs: { + nodes: { + terms: { + field: 'node_stats.node_id', + size, + }, + aggs: { + index: { + terms: { + field: '_index', + size: 1, + }, }, - aggs: { - index: { - terms: { - field: '_index', - size: 1, - }, + average_cpu: { + avg: { + field: 'node_stats.process.cpu.percent', }, - average_cpu: { - avg: { - field: 'node_stats.process.cpu.percent', - }, + }, + average_quota: { + avg: { + field: 'node_stats.os.cgroup.cpu.cfs_quota_micros', }, - average_quota: { - avg: { - field: 'node_stats.os.cgroup.cpu.cfs_quota_micros', - }, + }, + name: { + terms: { + field: 'source_node.name', + size: 1, }, - name: { - terms: { - field: 'source_node.name', - size: 1, - }, + }, + histo: { + date_histogram: { + field: 'timestamp', + fixed_interval: `${intervalInMinutes}m`, }, - histo: { - date_histogram: { - field: 'timestamp', - fixed_interval: `${intervalInMinutes}m`, - }, - aggs: { - average_periods: { - max: { - field: 'node_stats.os.cgroup.cpu.stat.number_of_elapsed_periods', - }, + aggs: { + average_periods: { + max: { + field: 'node_stats.os.cgroup.cpu.stat.number_of_elapsed_periods', }, - average_usage: { - max: { - field: 'node_stats.os.cgroup.cpuacct.usage_nanos', - }, + }, + average_usage: { + max: { + field: 'node_stats.os.cgroup.cpuacct.usage_nanos', }, - usage_deriv: { - derivative: { - buckets_path: 'average_usage', - gap_policy: 'skip' as const, - unit: NORMALIZED_DERIVATIVE_UNIT, - }, + }, + usage_deriv: { + derivative: { + buckets_path: 'average_usage', + gap_policy: 'skip' as const, + unit: NORMALIZED_DERIVATIVE_UNIT, }, - periods_deriv: { - derivative: { - buckets_path: 'average_periods', - gap_policy: 'skip' as const, - unit: NORMALIZED_DERIVATIVE_UNIT, - }, + }, + periods_deriv: { + derivative: { + buckets_path: 'average_periods', + gap_policy: 'skip' as const, + unit: NORMALIZED_DERIVATIVE_UNIT, }, }, }, @@ -150,7 +148,7 @@ export async function fetchCpuUsageNodeStats( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.test.ts index a292abf3720fd..061a6fab22d55 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.test.ts @@ -91,50 +91,48 @@ describe('fetchDiskUsageNodeStats', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.node_stats-*,metrics-elasticsearch.stack_monitoring.node_stats-*', filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['cluster123'] } }, - { - bool: { - should: [ - { term: { type: 'node_stats' } }, - { term: { 'metricset.name': 'node_stats' } }, - { - term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, - }, - ], - minimum_should_match: 1, - }, + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['cluster123'] } }, + { + bool: { + should: [ + { term: { type: 'node_stats' } }, + { term: { 'metricset.name': 'node_stats' } }, + { + term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-5m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-5m' } } }, + ], }, - aggs: { - clusters: { - terms: { field: 'cluster_uuid', size: 10, include: ['cluster123'] }, - aggs: { - nodes: { - terms: { field: 'node_stats.node_id', size: 10 }, - aggs: { - index: { terms: { field: '_index', size: 1 } }, - total_in_bytes: { max: { field: 'node_stats.fs.total.total_in_bytes' } }, - available_in_bytes: { max: { field: 'node_stats.fs.total.available_in_bytes' } }, - usage_ratio_percentile: { - bucket_script: { - buckets_path: { - available_in_bytes: 'available_in_bytes', - total_in_bytes: 'total_in_bytes', - }, - script: - '100 - Math.floor((params.available_in_bytes / params.total_in_bytes) * 100)', + }, + aggs: { + clusters: { + terms: { field: 'cluster_uuid', size: 10, include: ['cluster123'] }, + aggs: { + nodes: { + terms: { field: 'node_stats.node_id', size: 10 }, + aggs: { + index: { terms: { field: '_index', size: 1 } }, + total_in_bytes: { max: { field: 'node_stats.fs.total.total_in_bytes' } }, + available_in_bytes: { max: { field: 'node_stats.fs.total.available_in_bytes' } }, + usage_ratio_percentile: { + bucket_script: { + buckets_path: { + available_in_bytes: 'available_in_bytes', + total_in_bytes: 'total_in_bytes', }, + script: + '100 - Math.floor((params.available_in_bytes / params.total_in_bytes) * 100)', }, - name: { terms: { field: 'source_node.name', size: 1 } }, }, + name: { terms: { field: 'source_node.name', size: 1 } }, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.ts index 1c8f9808a04a5..254919e544b7d 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_disk_usage_node_stats.ts @@ -30,72 +30,70 @@ export async function fetchDiskUsageNodeStats( const params = { index: indexPatterns, filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clustersIds, - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clustersIds, }, - createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), - { - range: { - timestamp: { - gte: `now-${duration}`, - }, + }, + createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), + { + range: { + timestamp: { + gte: `now-${duration}`, }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - field: 'cluster_uuid', - size, - include: clustersIds, }, - aggs: { - nodes: { - terms: { - field: 'node_stats.node_id', - size, - }, - aggs: { - index: { - terms: { - field: '_index', - size: 1, - }, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + include: clustersIds, + }, + aggs: { + nodes: { + terms: { + field: 'node_stats.node_id', + size, + }, + aggs: { + index: { + terms: { + field: '_index', + size: 1, }, - total_in_bytes: { - max: { - field: 'node_stats.fs.total.total_in_bytes', - }, + }, + total_in_bytes: { + max: { + field: 'node_stats.fs.total.total_in_bytes', }, - available_in_bytes: { - max: { - field: 'node_stats.fs.total.available_in_bytes', - }, + }, + available_in_bytes: { + max: { + field: 'node_stats.fs.total.available_in_bytes', }, - usage_ratio_percentile: { - bucket_script: { - buckets_path: { - available_in_bytes: 'available_in_bytes', - total_in_bytes: 'total_in_bytes', - }, - script: - '100 - Math.floor((params.available_in_bytes / params.total_in_bytes) * 100)', + }, + usage_ratio_percentile: { + bucket_script: { + buckets_path: { + available_in_bytes: 'available_in_bytes', + total_in_bytes: 'total_in_bytes', }, + script: + '100 - Math.floor((params.available_in_bytes / params.total_in_bytes) * 100)', }, - name: { - terms: { - field: 'source_node.name', - size: 1, - }, + }, + name: { + terms: { + field: 'source_node.name', + size: 1, }, }, }, @@ -108,7 +106,7 @@ export async function fetchDiskUsageNodeStats( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts index 440f0654e9944..04c9ddaba4abb 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts @@ -7,7 +7,7 @@ import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { fetchElasticsearchVersions } from './fetch_elasticsearch_versions'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; jest.mock('../../static_globals', () => ({ Globals: { @@ -75,33 +75,31 @@ describe('fetchElasticsearchVersions', () => { 'hits.hits._source.cluster_uuid', 'hits.hits._source.elasticsearch.cluster.id', ], - body: { - size: 1, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['cluster123'] } }, - { - bool: { - should: [ - { term: { type: 'cluster_stats' } }, - { term: { 'metricset.name': 'cluster_stats' } }, - { - term: { - 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', - }, + size: 1, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['cluster123'] } }, + { + bool: { + should: [ + { term: { type: 'cluster_stats' } }, + { term: { 'metricset.name': 'cluster_stats' } }, + { + term: { + 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-2m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-2m' } } }, + ], }, - collapse: { field: 'cluster_uuid' }, }, + collapse: { field: 'cluster_uuid' }, }); }); it('should call ES with correct query when ccs disabled', async () => { diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.ts index a82cb77c047af..226f2175bc03a 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_elasticsearch_versions.ts @@ -33,49 +33,47 @@ export async function fetchElasticsearchVersions( 'hits.hits._source.cluster_uuid', 'hits.hits._source.elasticsearch.cluster.id', ], - body: { - size: clusters.length, - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + size: clusters.length, + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + }, + ], + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter( - 'cluster_stats', - 'cluster_stats', - getElasticsearchDataset('cluster_stats') - ), - { - range: { - timestamp: { - gte: 'now-2m', - }, + }, + createDatasetFilter( + 'cluster_stats', + 'cluster_stats', + getElasticsearchDataset('cluster_stats') + ), + { + range: { + timestamp: { + gte: 'now-2m', }, }, - ], - }, - }, - collapse: { - field: 'cluster_uuid', + }, + ], }, }, + collapse: { + field: 'cluster_uuid', + }, }; try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.test.ts index c00facef1df78..7a05c383bd474 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.test.ts @@ -7,7 +7,7 @@ import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { fetchIndexShardSize } from './fetch_index_shard_size'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; jest.mock('../../static_globals', () => ({ Globals: { @@ -223,46 +223,44 @@ describe('fetchIndexShardSize', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.index-*,metrics-elasticsearch.stack_monitoring.index-*', filter_path: ['aggregations.clusters.buckets'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - bool: { - should: [ - { term: { type: 'index_stats' } }, - { term: { 'metricset.name': 'index' } }, - { term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.index' } }, - ], - minimum_should_match: 1, - }, + size: 0, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { term: { type: 'index_stats' } }, + { term: { 'metricset.name': 'index' } }, + { term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.index' } }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-5m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-5m' } } }, + ], }, - aggs: { - clusters: { - terms: { include: ['cluster123'], field: 'cluster_uuid', size: 10 }, - aggs: { - index: { - terms: { field: 'index_stats.index', size: 10 }, - aggs: { - hits: { - top_hits: { - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - _source: { - includes: [ - '_index', - 'index_stats.shards.primaries', - 'index_stats.primaries.store.size_in_bytes', - 'elasticsearch.index.shards.primaries', - 'elasticsearch.index.primaries.store.size_in_bytes', - ], - }, - size: 1, + }, + aggs: { + clusters: { + terms: { include: ['cluster123'], field: 'cluster_uuid', size: 10 }, + aggs: { + index: { + terms: { field: 'index_stats.index', size: 10 }, + aggs: { + hits: { + top_hits: { + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + _source: { + includes: [ + '_index', + 'index_stats.shards.primaries', + 'index_stats.primaries.store.size_in_bytes', + 'elasticsearch.index.shards.primaries', + 'elasticsearch.index.primaries.store.size_in_bytes', + ], }, + size: 1, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.ts index 7b5affc78702a..543320051b654 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_index_shard_size.ts @@ -45,57 +45,55 @@ export async function fetchIndexShardSize( const params = { index: indexPatterns, filter_path: ['aggregations.clusters.buckets'], - body: { - size: 0, - query: { - bool: { - filter: [ - createDatasetFilter('index_stats', 'index', getElasticsearchDataset('index')), - { - range: { - timestamp: { - gte: 'now-5m', - }, + size: 0, + query: { + bool: { + filter: [ + createDatasetFilter('index_stats', 'index', getElasticsearchDataset('index')), + { + range: { + timestamp: { + gte: 'now-5m', }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - include: clusters.map((cluster) => cluster.clusterUuid), - field: 'cluster_uuid', - size, }, - aggs: { - index: { - terms: { - field: 'index_stats.index', - size, - }, - aggs: { - hits: { - top_hits: { - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + ], + }, + }, + aggs: { + clusters: { + terms: { + include: clusters.map((cluster) => cluster.clusterUuid), + field: 'cluster_uuid', + size, + }, + aggs: { + index: { + terms: { + field: 'index_stats.index', + size, + }, + aggs: { + hits: { + top_hits: { + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - _source: { - includes: [ - '_index', - 'index_stats.shards.primaries', - 'index_stats.primaries.store.size_in_bytes', - 'elasticsearch.index.shards.primaries', - 'elasticsearch.index.primaries.store.size_in_bytes', - ], }, - size: 1, + ], + _source: { + includes: [ + '_index', + 'index_stats.shards.primaries', + 'index_stats.primaries.store.size_in_bytes', + 'elasticsearch.index.shards.primaries', + 'elasticsearch.index.primaries.store.size_in_bytes', + ], }, + size: 1, }, }, }, @@ -108,7 +106,7 @@ export async function fetchIndexShardSize( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.test.ts index 59a6453102d46..833ea7212610e 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.test.ts @@ -92,42 +92,40 @@ describe('fetchKibanaVersions', () => { index: '*:.monitoring-kibana-*,.monitoring-kibana-*,*:metrics-kibana.stack_monitoring.stats-*,metrics-kibana.stack_monitoring.stats-*', filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['cluster123'] } }, - { - bool: { - should: [ - { term: { type: 'kibana_stats' } }, - { term: { 'metricset.name': 'stats' } }, - { term: { 'data_stream.dataset': 'kibana.stack_monitoring.stats' } }, - ], - minimum_should_match: 1, - }, + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['cluster123'] } }, + { + bool: { + should: [ + { term: { type: 'kibana_stats' } }, + { term: { 'metricset.name': 'stats' } }, + { term: { 'data_stream.dataset': 'kibana.stack_monitoring.stats' } }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-2m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-2m' } } }, + ], }, - aggs: { - index: { terms: { field: '_index', size: 1 } }, - cluster: { - terms: { field: 'cluster_uuid', size: 1 }, - aggs: { - group_by_kibana: { - terms: { field: 'kibana_stats.kibana.uuid', size: 10 }, - aggs: { - group_by_version: { - terms: { - field: 'kibana_stats.kibana.version', - size: 1, - order: { latest_report: 'desc' }, - }, - aggs: { latest_report: { max: { field: 'timestamp' } } }, + }, + aggs: { + index: { terms: { field: '_index', size: 1 } }, + cluster: { + terms: { field: 'cluster_uuid', size: 1 }, + aggs: { + group_by_kibana: { + terms: { field: 'kibana_stats.kibana.uuid', size: 10 }, + aggs: { + group_by_version: { + terms: { + field: 'kibana_stats.kibana.version', + size: 1, + order: { latest_report: 'desc' }, }, + aggs: { latest_report: { max: { field: 'timestamp' } } }, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.ts index 3f6282c049aa7..0a17bd9ecb6d6 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_kibana_versions.ts @@ -31,59 +31,57 @@ export async function fetchKibanaVersions( const params = { index: indexPatterns, filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter('kibana_stats', 'stats', getKibanaDataset('stats')), - { - range: { - timestamp: { - gte: 'now-2m', - }, + }, + createDatasetFilter('kibana_stats', 'stats', getKibanaDataset('stats')), + { + range: { + timestamp: { + gte: 'now-2m', }, }, - ], + }, + ], + }, + }, + aggs: { + index: { + terms: { + field: '_index', + size: 1, }, }, - aggs: { - index: { - terms: { - field: '_index', - size: 1, - }, + cluster: { + terms: { + field: 'cluster_uuid', + size: 1, }, - cluster: { - terms: { - field: 'cluster_uuid', - size: 1, - }, - aggs: { - group_by_kibana: { - terms: { - field: 'kibana_stats.kibana.uuid', - size, - }, - aggs: { - group_by_version: { - terms: { - field: 'kibana_stats.kibana.version', - size: 1, - order: { - latest_report: 'desc' as const, - }, + aggs: { + group_by_kibana: { + terms: { + field: 'kibana_stats.kibana.uuid', + size, + }, + aggs: { + group_by_version: { + terms: { + field: 'kibana_stats.kibana.version', + size: 1, + order: { + latest_report: 'desc' as const, }, - aggs: { - latest_report: { - max: { - field: 'timestamp', - }, + }, + aggs: { + latest_report: { + max: { + field: 'timestamp', }, }, }, @@ -98,7 +96,7 @@ export async function fetchKibanaVersions( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.test.ts index 7e5a8c1b4f920..fa07f16dff1ed 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.test.ts @@ -60,7 +60,7 @@ describe('fetchLicenses', () => { const clusters = [{ clusterUuid, clusterName }]; await fetchLicenses(esClient, clusters); const params = esClient.search.mock.calls[0][0] as any; - expect(params?.body?.query.bool.filter[0].terms.cluster_uuid).toEqual([clusterUuid]); + expect(params?.query.bool.filter[0].terms.cluster_uuid).toEqual([clusterUuid]); }); it('should limit the time period in the query', async () => { @@ -68,7 +68,7 @@ describe('fetchLicenses', () => { const clusters = [{ clusterUuid, clusterName }]; await fetchLicenses(esClient, clusters); const params = esClient.search.mock.calls[0][0] as any; - expect(params?.body?.query.bool.filter[2].range.timestamp.gte).toBe('now-2m'); + expect(params?.query.bool.filter[2].range.timestamp.gte).toBe('now-2m'); }); it('should call ES with correct query', async () => { const esClient = elasticsearchServiceMock.createScopedClusterClient().asCurrentUser; @@ -89,33 +89,31 @@ describe('fetchLicenses', () => { 'hits.hits._source.elasticsearch.cluster.id', 'hits.hits._index', ], - body: { - size: 1, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['clusterA'] } }, - { - bool: { - should: [ - { term: { type: 'cluster_stats' } }, - { term: { 'metricset.name': 'cluster_stats' } }, - { - term: { - 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', - }, + size: 1, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['clusterA'] } }, + { + bool: { + should: [ + { term: { type: 'cluster_stats' } }, + { term: { 'metricset.name': 'cluster_stats' } }, + { + term: { + 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-2m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-2m' } } }, + ], }, - collapse: { field: 'cluster_uuid' }, }, + collapse: { field: 'cluster_uuid' }, }); }); it('should call ES with correct query when ccs disabled', async () => { diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.ts index b7216b259302a..ed85ab6bd58c9 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_licenses.ts @@ -32,49 +32,47 @@ export async function fetchLicenses( 'hits.hits._source.elasticsearch.cluster.id', 'hits.hits._index', ], - body: { - size: clusters.length, - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + size: clusters.length, + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + }, + ], + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter( - 'cluster_stats', - 'cluster_stats', - getElasticsearchDataset('cluster_stats') - ), - { - range: { - timestamp: { - gte: 'now-2m', - }, + }, + createDatasetFilter( + 'cluster_stats', + 'cluster_stats', + getElasticsearchDataset('cluster_stats') + ), + { + range: { + timestamp: { + gte: 'now-2m', }, }, - ], - }, - }, - collapse: { - field: 'cluster_uuid', + }, + ], }, }, + collapse: { + field: 'cluster_uuid', + }, }; try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.test.ts index fbdd305547a16..24f2f00138cd9 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.test.ts @@ -97,42 +97,40 @@ describe('fetchLogstashVersions', () => { index: '*:.monitoring-logstash-*,.monitoring-logstash-*,*:metrics-logstash.stack_monitoring.node_stats-*,metrics-logstash.stack_monitoring.node_stats-*', filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['cluster123'] } }, - { - bool: { - should: [ - { term: { type: 'logstash_stats' } }, - { term: { 'metricset.name': 'node_stats' } }, - { term: { 'data_stream.dataset': 'logstash.stack_monitoring.node_stats' } }, - ], - minimum_should_match: 1, - }, + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['cluster123'] } }, + { + bool: { + should: [ + { term: { type: 'logstash_stats' } }, + { term: { 'metricset.name': 'node_stats' } }, + { term: { 'data_stream.dataset': 'logstash.stack_monitoring.node_stats' } }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-2m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-2m' } } }, + ], }, - aggs: { - index: { terms: { field: '_index', size: 1 } }, - cluster: { - terms: { field: 'cluster_uuid', size: 1 }, - aggs: { - group_by_logstash: { - terms: { field: 'logstash_stats.logstash.uuid', size: 10 }, - aggs: { - group_by_version: { - terms: { - field: 'logstash_stats.logstash.version', - size: 1, - order: { latest_report: 'desc' }, - }, - aggs: { latest_report: { max: { field: 'timestamp' } } }, + }, + aggs: { + index: { terms: { field: '_index', size: 1 } }, + cluster: { + terms: { field: 'cluster_uuid', size: 1 }, + aggs: { + group_by_logstash: { + terms: { field: 'logstash_stats.logstash.uuid', size: 10 }, + aggs: { + group_by_version: { + terms: { + field: 'logstash_stats.logstash.version', + size: 1, + order: { latest_report: 'desc' }, }, + aggs: { latest_report: { max: { field: 'timestamp' } } }, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.ts index 5bbaf32442694..0428f638035c9 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_logstash_versions.ts @@ -31,59 +31,57 @@ export async function fetchLogstashVersions( const params = { index: indexPatterns, filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter('logstash_stats', 'node_stats', getLogstashDataset('node_stats')), - { - range: { - timestamp: { - gte: 'now-2m', - }, + }, + createDatasetFilter('logstash_stats', 'node_stats', getLogstashDataset('node_stats')), + { + range: { + timestamp: { + gte: 'now-2m', }, }, - ], + }, + ], + }, + }, + aggs: { + index: { + terms: { + field: '_index', + size: 1, }, }, - aggs: { - index: { - terms: { - field: '_index', - size: 1, - }, + cluster: { + terms: { + field: 'cluster_uuid', + size: 1, }, - cluster: { - terms: { - field: 'cluster_uuid', - size: 1, - }, - aggs: { - group_by_logstash: { - terms: { - field: 'logstash_stats.logstash.uuid', - size, - }, - aggs: { - group_by_version: { - terms: { - field: 'logstash_stats.logstash.version', - size: 1, - order: { - latest_report: 'desc' as const, - }, + aggs: { + group_by_logstash: { + terms: { + field: 'logstash_stats.logstash.uuid', + size, + }, + aggs: { + group_by_version: { + terms: { + field: 'logstash_stats.logstash.version', + size: 1, + order: { + latest_report: 'desc' as const, }, - aggs: { - latest_report: { - max: { - field: 'timestamp', - }, + }, + aggs: { + latest_report: { + max: { + field: 'timestamp', }, }, }, @@ -98,7 +96,7 @@ export async function fetchLogstashVersions( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.test.ts index cf295c5fec3eb..6c1c04a8110d2 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.test.ts @@ -119,40 +119,38 @@ describe('fetchMemoryUsageNodeStats', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.node_stats-*,metrics-elasticsearch.stack_monitoring.node_stats-*', filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['abc123'] } }, - { - bool: { - should: [ - { term: { type: 'node_stats' } }, - { term: { 'metricset.name': 'node_stats' } }, - { - term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, - }, - ], - minimum_should_match: 1, - }, + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['abc123'] } }, + { + bool: { + should: [ + { term: { type: 'node_stats' } }, + { term: { 'metricset.name': 'node_stats' } }, + { + term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { format: 'epoch_millis', gte: 0, lte: 0 } } }, - ], - }, + }, + { range: { timestamp: { format: 'epoch_millis', gte: 0, lte: 0 } } }, + ], }, - aggs: { - clusters: { - terms: { field: 'cluster_uuid', size: 10 }, - aggs: { - nodes: { - terms: { field: 'source_node.uuid', size: 10 }, - aggs: { - index: { terms: { field: '_index', size: 1 } }, - avg_heap: { avg: { field: 'node_stats.jvm.mem.heap_used_percent' } }, - cluster_uuid: { terms: { field: 'cluster_uuid', size: 1 } }, - name: { terms: { field: 'source_node.name', size: 1 } }, - }, + }, + aggs: { + clusters: { + terms: { field: 'cluster_uuid', size: 10 }, + aggs: { + nodes: { + terms: { field: 'source_node.uuid', size: 10 }, + aggs: { + index: { terms: { field: '_index', size: 1 } }, + avg_heap: { avg: { field: 'node_stats.jvm.mem.heap_used_percent' } }, + cluster_uuid: { terms: { field: 'cluster_uuid', size: 1 } }, + name: { terms: { field: 'source_node.name', size: 1 } }, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.ts index da943945aebce..2fe96da703272 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_memory_usage_node_stats.ts @@ -31,64 +31,62 @@ export async function fetchMemoryUsageNodeStats( const params = { index: indexPatterns, filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clustersIds, - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clustersIds, }, - createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), - { - range: { - timestamp: { - format: 'epoch_millis', - gte: startMs, - lte: endMs, - }, + }, + createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), + { + range: { + timestamp: { + format: 'epoch_millis', + gte: startMs, + lte: endMs, }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - field: 'cluster_uuid', - size, }, - aggs: { - nodes: { - terms: { - field: 'source_node.uuid', - size, - }, - aggs: { - index: { - terms: { - field: '_index', - size: 1, - }, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + }, + aggs: { + nodes: { + terms: { + field: 'source_node.uuid', + size, + }, + aggs: { + index: { + terms: { + field: '_index', + size: 1, }, - avg_heap: { - avg: { - field: 'node_stats.jvm.mem.heap_used_percent', - }, + }, + avg_heap: { + avg: { + field: 'node_stats.jvm.mem.heap_used_percent', }, - cluster_uuid: { - terms: { - field: 'cluster_uuid', - size: 1, - }, + }, + cluster_uuid: { + terms: { + field: 'cluster_uuid', + size: 1, }, - name: { - terms: { - field: 'source_node.name', - size: 1, - }, + }, + name: { + terms: { + field: 'source_node.name', + size: 1, }, }, }, @@ -101,7 +99,7 @@ export async function fetchMemoryUsageNodeStats( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.test.ts index 7a70a8594936f..e9430f11e025b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.test.ts @@ -178,43 +178,41 @@ describe('fetchMissingMonitoringData', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.node_stats-*,metrics-elasticsearch.stack_monitoring.node_stats-*', filter_path: ['aggregations.clusters.buckets'], - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { cluster_uuid: ['clusterUuid1'] } }, - { - bool: { - should: [ - { term: { type: 'node_stats' } }, - { term: { 'metricset.name': 'node_stats' } }, - { - term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, - }, - ], - minimum_should_match: 1, - }, + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: ['clusterUuid1'] } }, + { + bool: { + should: [ + { term: { type: 'node_stats' } }, + { term: { 'metricset.name': 'node_stats' } }, + { + term: { 'data_stream.dataset': 'elasticsearch.stack_monitoring.node_stats' }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { format: 'epoch_millis', gte: 100, lte: 10 } } }, - ], - }, + }, + { range: { timestamp: { format: 'epoch_millis', gte: 100, lte: 10 } } }, + ], }, - aggs: { - clusters: { - terms: { field: 'cluster_uuid', size: 10 }, - aggs: { - es_uuids: { - terms: { field: 'node_stats.node_id', size: 10 }, - aggs: { - most_recent: { max: { field: 'timestamp' } }, - document: { - top_hits: { - size: 1, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - _source: { - includes: ['source_node.name', 'elasticsearch.node.name'], - }, + }, + aggs: { + clusters: { + terms: { field: 'cluster_uuid', size: 10 }, + aggs: { + es_uuids: { + terms: { field: 'node_stats.node_id', size: 10 }, + aggs: { + most_recent: { max: { field: 'timestamp' } }, + document: { + top_hits: { + size: 1, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + _source: { + includes: ['source_node.name', 'elasticsearch.node.name'], }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.ts index 5343604011710..eb2553cc4469d 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_missing_monitoring_data.ts @@ -64,61 +64,59 @@ export async function fetchMissingMonitoringData( const params = { index: indexPatterns, filter_path: ['aggregations.clusters.buckets'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), }, - createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), - { - range: { - timestamp: { - format: 'epoch_millis', - gte: startMs, - lte: endMs, - }, + }, + createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), + { + range: { + timestamp: { + format: 'epoch_millis', + gte: startMs, + lte: endMs, }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - field: 'cluster_uuid', - size, }, - aggs: { - es_uuids: { - terms: { - field: 'node_stats.node_id', - size, - }, - aggs: { - most_recent: { - max: { - field: 'timestamp', - }, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + }, + aggs: { + es_uuids: { + terms: { + field: 'node_stats.node_id', + size, + }, + aggs: { + most_recent: { + max: { + field: 'timestamp', }, - document: { - top_hits: { - size: 1, - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + }, + document: { + top_hits: { + size: 1, + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - _source: { - includes: ['source_node.name', 'elasticsearch.node.name'], }, + ], + _source: { + includes: ['source_node.name', 'elasticsearch.node.name'], }, }, }, @@ -132,7 +130,7 @@ export async function fetchMissingMonitoringData( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.test.ts index 780804c2fe24d..f20161ba80680 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.test.ts @@ -287,42 +287,40 @@ describe('fetchNodesFromClusterStats', () => { index: '*:.monitoring-es-*,.monitoring-es-*,*:metrics-elasticsearch.stack_monitoring.cluster_stats-*,metrics-elasticsearch.stack_monitoring.cluster_stats-*', filter_path: ['aggregations.clusters.buckets'], - body: { - size: 0, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - query: { - bool: { - filter: [ - { - bool: { - should: [ - { term: { type: 'cluster_stats' } }, - { term: { 'metricset.name': 'cluster_stats' } }, - { - term: { - 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', - }, + size: 0, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + query: { + bool: { + filter: [ + { + bool: { + should: [ + { term: { type: 'cluster_stats' } }, + { term: { 'metricset.name': 'cluster_stats' } }, + { + term: { + 'data_stream.dataset': 'elasticsearch.stack_monitoring.cluster_stats', }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - { range: { timestamp: { gte: 'now-2m' } } }, - ], - }, + }, + { range: { timestamp: { gte: 'now-2m' } } }, + ], }, - aggs: { - clusters: { - terms: { include: ['NG2d5jHiSBGPE6HLlUN2Bg'], field: 'cluster_uuid' }, - aggs: { - top: { - top_hits: { - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - _source: { - includes: ['cluster_state.nodes', 'elasticsearch.cluster.stats.state.nodes'], - }, - size: 2, + }, + aggs: { + clusters: { + terms: { include: ['NG2d5jHiSBGPE6HLlUN2Bg'], field: 'cluster_uuid' }, + aggs: { + top: { + top_hits: { + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + _source: { + includes: ['cluster_state.nodes', 'elasticsearch.cluster.stats.state.nodes'], }, + size: 2, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.ts index f4cf1f5cb4f7a..336265388d063 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_nodes_from_cluster_stats.ts @@ -41,56 +41,54 @@ export async function fetchNodesFromClusterStats( const params = { index: indexPatterns, filter_path: ['aggregations.clusters.buckets'], - body: { - size: 0, - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + size: 0, + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - query: { - bool: { - filter: [ - createDatasetFilter( - 'cluster_stats', - 'cluster_stats', - getElasticsearchDataset('cluster_stats') - ), - { - range: { - timestamp: { - gte: 'now-2m', - }, + }, + ], + query: { + bool: { + filter: [ + createDatasetFilter( + 'cluster_stats', + 'cluster_stats', + getElasticsearchDataset('cluster_stats') + ), + { + range: { + timestamp: { + gte: 'now-2m', }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - include: clusters.map((cluster) => cluster.clusterUuid), - field: 'cluster_uuid', }, - aggs: { - top: { - top_hits: { - sort: [ - { - timestamp: { - order: 'desc' as const, - unmapped_type: 'long' as const, - }, + ], + }, + }, + aggs: { + clusters: { + terms: { + include: clusters.map((cluster) => cluster.clusterUuid), + field: 'cluster_uuid', + }, + aggs: { + top: { + top_hits: { + sort: [ + { + timestamp: { + order: 'desc' as const, + unmapped_type: 'long' as const, }, - ], - _source: { - includes: ['cluster_state.nodes', 'elasticsearch.cluster.stats.state.nodes'], }, - size: 2, + ], + _source: { + includes: ['cluster_state.nodes', 'elasticsearch.cluster.stats.state.nodes'], }, + size: 2, }, }, }, @@ -101,7 +99,7 @@ export async function fetchNodesFromClusterStats( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_thread_pool_rejections_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_thread_pool_rejections_stats.ts index 3e26d9eb77028..bfd3757e37d16 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_thread_pool_rejections_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/alerts/fetch_thread_pool_rejections_stats.ts @@ -57,46 +57,44 @@ export async function fetchThreadPoolRejectionStats( const params = { index: indexPatterns, filter_path: ['aggregations'], - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clustersIds, - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clustersIds, }, - createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), - { - range: { - timestamp: { - gte: `now-${duration}`, - }, + }, + createDatasetFilter('node_stats', 'node_stats', getElasticsearchDataset('node_stats')), + { + range: { + timestamp: { + gte: `now-${duration}`, }, }, - ], - }, - }, - aggs: { - clusters: { - terms: { - field: 'cluster_uuid', - size, }, - aggs: { - nodes: { - terms: { - field: 'source_node.uuid', - size, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + }, + aggs: { + nodes: { + terms: { + field: 'source_node.uuid', + size, + }, + aggs: { + most_recent: { + ...getTopHits(threadType, 'desc' as const), }, - aggs: { - most_recent: { - ...getTopHits(threadType, 'desc' as const), - }, - least_recent: { - ...getTopHits(threadType, 'asc' as const), - }, + least_recent: { + ...getTopHits(threadType, 'asc' as const), }, }, }, @@ -108,7 +106,7 @@ export async function fetchThreadPoolRejectionStats( try { if (filterQuery) { const filterQueryObject = JSON.parse(filterQuery); - params.body.query.bool.filter.push(filterQueryObject); + params.query.bool.filter.push(filterQueryObject); } } catch (e) { // meh diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/apm/_get_time_of_last_event.ts b/x-pack/platform/plugins/private/monitoring/server/lib/apm/_get_time_of_last_event.ts index d4580ab1e0a90..170df4519a1e3 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/apm/_get_time_of_last_event.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/apm/_get_time_of_last_event.ts @@ -29,32 +29,30 @@ export async function getTimeOfLastEvent({ index: apmIndexPattern, size: 1, ignore_unavailable: true, - body: { - _source: ['beats_stats.timestamp', '@timestamp'], - sort: [ + _source: ['beats_stats.timestamp', '@timestamp'], + sort: [ + { + timestamp: { + order: 'desc', + unmapped_type: 'long', + }, + }, + ], + query: createApmQuery({ + start, + end, + clusterUuid, + metric: ApmClusterMetric.getMetricFields(), + filters: [ { - timestamp: { - order: 'desc', - unmapped_type: 'long', + range: { + 'beats_stats.metrics.libbeat.output.events.acked': { + gt: 0, + }, }, }, ], - query: createApmQuery({ - start, - end, - clusterUuid, - metric: ApmClusterMetric.getMetricFields(), - filters: [ - { - range: { - 'beats_stats.metrics.libbeat.output.events.acked': { - gt: 0, - }, - }, - }, - ], - }), - }, + }), }; const response = await callWithRequest(req, 'search', params); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apm_info.ts b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apm_info.ts index a9ee65b2dd74d..0aeeedbcb8f92 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apm_info.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apm_info.ts @@ -128,25 +128,23 @@ export async function getApmInfo( 'hits.hits.inner_hits.first_hit.hits.hits._source.beat.stats.libbeat.pipeline.events.dropped', 'hits.hits.inner_hits.first_hit.hits.hits._source.beat.stats.libbeat.output.write.bytes', ], - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - start, - end, - clusterUuid, - metric: ApmMetric.getMetricFields(), - filters, - }), - collapse: { - field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restart - inner_hits: { - name: 'first_hit', - size: 1, - sort: [ - { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, - { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, - ], - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + start, + end, + clusterUuid, + metric: ApmMetric.getMetricFields(), + filters, + }), + collapse: { + field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restart + inner_hits: { + name: 'first_hit', + size: 1, + sort: [ + { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, + { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, + ], }, }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms.ts b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms.ts index d7c239a8d3641..8e7cb9ecc7e7e 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms.ts @@ -153,28 +153,26 @@ export async function getApms(req: LegacyRequest, apmIndexPattern: string, clust 'hits.hits.inner_hits.earliest.hits.hits._source.beats_stats.metrics.libbeat.output.read.errors', 'hits.hits.inner_hits.earliest.hits.hits._source.beats_stats.metrics.libbeat.output.write.errors', ], - body: { - query: createApmQuery({ - start, - end, - clusterUuid, - }), - collapse: { - field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restarts - inner_hits: { - name: 'earliest', - size: 1, - sort: [ - { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, - { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, - ], - }, + query: createApmQuery({ + start, + end, + clusterUuid, + }), + collapse: { + field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restarts + inner_hits: { + name: 'earliest', + size: 1, + sort: [ + { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, + { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, + ], }, - sort: [ - { 'beats_stats.beat.uuid': { order: 'asc', unmapped_type: 'long' } }, // need to keep duplicate uuids grouped - { timestamp: { order: 'desc', unmapped_type: 'long' } }, // need oldest timestamp to come first for rate calcs to work - ], }, + sort: [ + { 'beats_stats.beat.uuid': { order: 'asc', unmapped_type: 'long' } }, // need to keep duplicate uuids grouped + { timestamp: { order: 'desc', unmapped_type: 'long' } }, // need oldest timestamp to come first for rate calcs to work + ], }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms_for_clusters.ts index 5764d787142c9..5e3e941b1e0ac 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_apms_for_clusters.ts @@ -55,15 +55,13 @@ export function getApmsForClusters(req: LegacyRequest, clusters: Cluster[], ccs? size: 0, ignore_unavailable: true, filter_path: apmAggFilterPath, - body: { - query: createApmQuery({ - start, - end, - clusterUuid, - metric: ApmMetric.getMetricFields(), // override default of BeatMetric.getMetricFields - }), - aggs: apmUuidsAgg(maxBucketSize, cgroup), - }, + query: createApmQuery({ + start, + end, + clusterUuid, + metric: ApmMetric.getMetricFields(), // override default of BeatMetric.getMetricFields + }), + aggs: apmUuidsAgg(maxBucketSize, cgroup), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_stats.ts index e536972c7acb4..3d931e869da77 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/apm/get_stats.ts @@ -38,14 +38,12 @@ export async function getStats(req: LegacyRequest, apmIndexPattern: string, clus filter_path: apmAggFilterPath, size: 0, ignore_unavailable: true, - body: { - query: createApmQuery({ - start, - end, - clusterUuid, - }), - aggs: apmUuidsAgg(maxBucketSize, cgroup), - }, + query: createApmQuery({ + start, + end, + clusterUuid, + }), + aggs: apmUuidsAgg(maxBucketSize, cgroup), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beat_summary.ts b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beat_summary.ts index 8c20ccc8d8ee6..a85575e510c89 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beat_summary.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beat_summary.ts @@ -123,24 +123,22 @@ export async function getBeatSummary( 'hits.hits.inner_hits.first_hit.hits.hits._source.beats_stats.metrics.libbeat.output.write.bytes', 'hits.hits.inner_hits.first_hit.hits.hits._source.beat.stats.libbeat.output.write.bytes', ], - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createBeatsQuery({ - start, - end, - clusterUuid, - filters, - }), - collapse: { - field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restart - inner_hits: { - name: 'first_hit', - size: 1, - sort: [ - { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, - { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, - ], - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createBeatsQuery({ + start, + end, + clusterUuid, + filters, + }), + collapse: { + field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restart + inner_hits: { + name: 'first_hit', + size: 1, + sort: [ + { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, + { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, + ], }, }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats.ts index f5ca1b7acb985..2a9950e3b0475 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats.ts @@ -161,28 +161,26 @@ export async function getBeats(req: LegacyRequest, beatsIndexPattern: string, cl 'hits.hits.inner_hits.earliest.hits.hits._source.beats_stats.metrics.libbeat.output.write.errors', 'hits.hits.inner_hits.earliest.hits.hits._source.beat.stats.libbeat.output.write.errors', ], - body: { - query: createBeatsQuery({ - start, - end, - clusterUuid, - }), - collapse: { - field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restarts - inner_hits: { - name: 'earliest', - size: 1, - sort: [ - { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, - { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, - ], - }, + query: createBeatsQuery({ + start, + end, + clusterUuid, + }), + collapse: { + field: 'beats_stats.metrics.beat.info.ephemeral_id', // collapse on ephemeral_id to handle restarts + inner_hits: { + name: 'earliest', + size: 1, + sort: [ + { 'beats_stats.timestamp': { order: 'asc', unmapped_type: 'long' } }, + { '@timestamp': { order: 'asc', unmapped_type: 'long' } }, + ], }, - sort: [ - { 'beats_stats.beat.uuid': { order: 'asc', unmapped_type: 'long' } }, // need to keep duplicate uuids grouped - { timestamp: { order: 'desc', unmapped_type: 'long' } }, // need oldest timestamp to come first for rate calcs to work - ], }, + sort: [ + { 'beats_stats.beat.uuid': { order: 'asc', unmapped_type: 'long' } }, // need to keep duplicate uuids grouped + { timestamp: { order: 'desc', unmapped_type: 'long' } }, // need oldest timestamp to come first for rate calcs to work + ], }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats_for_clusters.ts index 8e0a6236a2fd9..532cd7db073ec 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_beats_for_clusters.ts @@ -51,15 +51,13 @@ export function getBeatsForClusters(req: LegacyRequest, clusters: Cluster[], ccs size: 0, ignore_unavailable: true, filter_path: beatsAggFilterPath, - body: { - query: createBeatsQuery({ - start, - end, - clusterUuid, - metric: BeatsClusterMetric.getMetricFields(), // override default of BeatMetric.getMetricFields - }), - aggs: beatsUuidsAgg(maxBucketSize), - }, + query: createBeatsQuery({ + start, + end, + clusterUuid, + metric: BeatsClusterMetric.getMetricFields(), // override default of BeatMetric.getMetricFields + }), + aggs: beatsUuidsAgg(maxBucketSize), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_latest_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_latest_stats.ts index 62c128492f8ee..d7ea97295e300 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_latest_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_latest_stats.ts @@ -87,33 +87,31 @@ export function getLatestStats(req: LegacyRequest, beatsIndexPattern: string, cl size: 0, ignore_unavailable: true, filter_path: 'aggregations', - body: { - query: createBeatsQuery({ - clusterUuid, - filters: [lastDayFilter], - }), - aggs: { - active_counts: { - date_range: { - field: 'timestamp', - ranges: [ - { key: 'last1m', from: 'now-1m/m', to: 'now' }, - { key: 'last5m', from: 'now-5m/m', to: 'now' }, - { key: 'last20m', from: 'now-20m/m', to: 'now' }, - { key: 'last1h', from: 'now-1h/h', to: 'now' }, - { key: 'last1d', from: 'now-1d/d', to: 'now' }, - ], - }, - ...beatUuidAgg, - }, - versions: { - terms: { field: 'beats_stats.beat.version', size: 5 }, - ...beatUuidAgg, - }, - types: { - terms: { field: 'beats_stats.beat.type', size: 5 }, - ...beatUuidAgg, + query: createBeatsQuery({ + clusterUuid, + filters: [lastDayFilter], + }), + aggs: { + active_counts: { + date_range: { + field: 'timestamp', + ranges: [ + { key: 'last1m', from: 'now-1m/m', to: 'now' }, + { key: 'last5m', from: 'now-5m/m', to: 'now' }, + { key: 'last20m', from: 'now-20m/m', to: 'now' }, + { key: 'last1h', from: 'now-1h/h', to: 'now' }, + { key: 'last1d', from: 'now-1d/d', to: 'now' }, + ], }, + ...beatUuidAgg, + }, + versions: { + terms: { field: 'beats_stats.beat.version', size: 5 }, + ...beatUuidAgg, + }, + types: { + terms: { field: 'beats_stats.beat.type', size: 5 }, + ...beatUuidAgg, }, }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_stats.ts index 1269255cd2b6e..a0649ebd600f0 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/beats/get_stats.ts @@ -38,14 +38,12 @@ export async function getStats(req: LegacyRequest, beatsIndexPattern: string, cl filter_path: beatsAggFilterPath, size: 0, ignore_unavailable: true, - body: { - query: createBeatsQuery({ - start, - end, - clusterUuid, - }), - aggs: beatsUuidsAgg(maxBucketSize!), - }, + query: createBeatsQuery({ + start, + end, + clusterUuid, + }), + aggs: beatsUuidsAgg(maxBucketSize!), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/flag_supported_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/flag_supported_clusters.ts index f5ea6aa19c0fe..de0c2fc69aabe 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/flag_supported_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/flag_supported_clusters.ts @@ -44,23 +44,21 @@ async function findSupportedBasicLicenseCluster( size: 1, ignore_unavailable: true, filter_path: ['hits.hits._source.cluster_uuid', 'hits.hits._source.cluster.id'], - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: { - bool: { - filter: [ - { - bool: { - should: [ - { term: { type: 'kibana_stats' } }, - { term: { 'data_stream.dataset': getKibanaDataset(dataset) } }, - ], - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { term: { type: 'kibana_stats' } }, + { term: { 'data_stream.dataset': getKibanaDataset(dataset) } }, + ], }, - { term: { 'kibana_stats.kibana.uuid': kibanaUuid } }, - { range: { timestamp: { gte, lte, format: 'epoch_millis' } } }, - ], - }, + }, + { term: { 'kibana_stats.kibana.uuid': kibanaUuid } }, + { range: { timestamp: { gte, lte, format: 'epoch_millis' } } }, + ], }, }, })) as ElasticsearchResponse; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_cluster_license.ts b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_cluster_license.ts index bc25cf3280182..11ad20ec88b6e 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_cluster_license.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_cluster_license.ts @@ -28,16 +28,14 @@ export function getClusterLicense(req: LegacyRequest, clusterUuid: string) { size: 1, ignore_unavailable: true, filter_path: ['hits.hits._source.license'], - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - clusterUuid, - metric: ElasticsearchMetric.getMetricFields(), - }), - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + clusterUuid, + metric: ElasticsearchMetric.getMetricFields(), + }), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_state.ts b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_state.ts index 4d6ca01e3e6e7..de5779c3e30bd 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_state.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_state.ts @@ -73,17 +73,15 @@ export function getClustersState(req: LegacyRequest, clusters: ElasticsearchModi 'hits.hits._source.cluster_state', 'hits.hits._source.elasticsearch.cluster.stats.state', ], - body: { - query: { - bool: { - filter: [{ term: { type: 'cluster_state' } }, { terms: { cluster_uuid: clusterUuids } }], - }, + query: { + bool: { + filter: [{ term: { type: 'cluster_state' } }, { terms: { cluster_uuid: clusterUuids } }], }, - collapse: { - field: 'cluster_uuid', - }, - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, }, + collapse: { + field: 'cluster_uuid', + }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_stats.ts index 59a66b8b9ea4d..1413bbb0b480a 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/cluster/get_clusters_stats.ts @@ -82,21 +82,19 @@ function fetchClusterStats(req: LegacyRequest, clusterUuid?: string, ccs?: strin 'hits.hits._source.elasticsearch.cluster.stats.state', 'hits.hits._source.cluster_settings.cluster.metadata.display_name', ], - body: { - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - metric, - clusterUuid, - }), - collapse: { - field: 'cluster_uuid', - }, - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + metric, + clusterUuid, + }), + collapse: { + field: 'cluster_uuid', }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/details/get_series.ts b/x-pack/platform/plugins/private/monitoring/server/lib/details/get_series.ts index 854c5a67db307..2d6e3dfa0dc1b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/details/get_series.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/details/get_series.ts @@ -184,20 +184,18 @@ async function fetchSeries( index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - query: createQuery({ - start: adjustedMin, - end: Number(max), - metric, - clusterUuid: metricOptions.skipClusterUuidFilter - ? STANDALONE_CLUSTER_CLUSTER_UUID - : req.params.clusterUuid, - // TODO: Pass in the UUID as an explicit function parameter - uuid: getUuid(req, metric), - filters, - }), - aggs, - }, + query: createQuery({ + start: adjustedMin, + end: Number(max), + metric, + clusterUuid: metricOptions.skipClusterUuidFilter + ? STANDALONE_CLUSTER_CLUSTER_UUID + : req.params.clusterUuid, + // TODO: Pass in the UUID as an explicit function parameter + uuid: getUuid(req, metric), + filters, + }), + aggs, }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/ccr.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/ccr.ts index f809e6e358e7c..88b56f30960b7 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/ccr.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/ccr.ts @@ -33,18 +33,16 @@ export async function checkCcrEnabled(req: LegacyRequest, ccs: string) { index: indexPatterns, size: 1, ignore_unavailable: true, - body: { - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric: metricFields, - }), - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - }, + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric: metricFields, + }), + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], filter_path: [ 'hits.hits._source.stack_stats.xpack.ccr', 'hits.hits._source.elasticsearch.cluster.stats.stack.xpack.ccr', diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_last_recovery.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_last_recovery.ts index baaa06c1421ab..0291358381e7b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_last_recovery.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_last_recovery.ts @@ -122,18 +122,16 @@ export async function getLastRecovery(req: LegacyRequest, size: number) { index: indexPattern, size: 1, ignore_unavailable: true, - body: { - _source: ['index_recovery.shards'], - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type: dataset, - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - }, + _source: ['index_recovery.shards'], + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type: dataset, + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), }; const indexPatternEcs = getIndexPatterns({ @@ -147,23 +145,21 @@ export async function getLastRecovery(req: LegacyRequest, size: number) { index: indexPatternEcs, size, ignore_unavailable: true, - body: { - _source: ['elasticsearch.index.recovery', '@timestamp'], - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - aggs: { - max_timestamp: { - max: { - field: '@timestamp', - }, + _source: ['elasticsearch.index.recovery', '@timestamp'], + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), + aggs: { + max_timestamp: { + max: { + field: '@timestamp', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_ml_jobs.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_ml_jobs.ts index ab724a2c49cf1..72f80b88b6b2a 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_ml_jobs.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/get_ml_jobs.ts @@ -73,19 +73,17 @@ export function getMlJobs(req: LegacyRequest) { 'hits.hits._source.job_stats.node.name', 'hits.hits._source.elasticsearch.node.name', ], - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - collapse: { field: 'job_stats.job_id' }, - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + collapse: { field: 'job_stats.job_id' }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); @@ -121,19 +119,17 @@ export function getMlJobsForCluster(req: LegacyRequest, cluster: Cluster, ccs: s size: 0, ignore_unavailable: true, filter_path: 'aggregations.jobs_count.value', - body: { - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - aggs: { - jobs_count: { cardinality: { field: 'job_stats.job_id' } }, - }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), + aggs: { + jobs_count: { cardinality: { field: 'job_stats.job_id' } }, }, }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_index_summary.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_index_summary.ts index 4da1099fd5836..eac798b660e5b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_index_summary.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_index_summary.ts @@ -95,19 +95,17 @@ export function getIndexSummary( index: indexPatterns, size: 1, ignore_unavailable: true, - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - filters, - }), - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + filters, + }), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_indices.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_indices.ts index 6b40c8480603d..b05e3c56e2681 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_indices.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/indices/get_indices.ts @@ -148,27 +148,25 @@ export function buildGetIndicesQuery( 'hits.hits.inner_hits.earliest.hits.hits._source.index_stats.total.search.query_total', 'hits.hits.inner_hits.earliest.hits.hits._source.elasticsearch.index.total.search.query_total', ], - body: { - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric: metricFields, - filters, - }), - collapse: { - field: 'index_stats.index', - inner_hits: { - name: 'earliest', - size: 1, - sort: [{ timestamp: { order: 'asc', unmapped_type: 'long' } }], - }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric: metricFields, + filters, + }), + collapse: { + field: 'index_stats.index', + inner_hits: { + name: 'earliest', + size: 1, + sort: [{ timestamp: { order: 'asc', unmapped_type: 'long' } }], }, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], }; } diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_node_summary.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_node_summary.ts index c050f5fac52b2..bfe7b423a3051 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_node_summary.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_node_summary.ts @@ -124,19 +124,17 @@ export function getNodeSummary( index: indexPatterns, size: 1, ignore_unavailable: true, - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - filters, - }), - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + filters, + }), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); return callWithRequest(req, 'search', params).then( diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_node_ids.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_node_ids.ts index 968e5200d7040..22d1d2eed35a7 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_node_ids.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_node_ids.ts @@ -38,37 +38,35 @@ export async function getNodeIds( size: 0, ignore_unavailable: true, filter_path: ['aggregations.composite_data.buckets'], - body: { - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - metric: ElasticsearchMetric.getMetricFields(), - clusterUuid, - }), - aggs: { - composite_data: { - composite: { - size, - sources: [ - { - name: { - terms: { - field: 'source_node.name', - }, + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + metric: ElasticsearchMetric.getMetricFields(), + clusterUuid, + }), + aggs: { + composite_data: { + composite: { + size, + sources: [ + { + name: { + terms: { + field: 'source_node.name', }, }, - { - uuid: { - terms: { - field: 'source_node.uuid', - }, + }, + { + uuid: { + terms: { + field: 'source_node.uuid', }, }, - ], - }, + }, + ], }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_nodes.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_nodes.ts index 66004202df261..71e58ebe0961f 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_nodes.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/nodes/get_nodes/get_nodes.ts @@ -83,41 +83,39 @@ export async function getNodes( index: indexPatterns, size: maxBucketSize, ignore_unavailable: true, - body: { - query: createQuery({ - type: dataset, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - filters, - metric: metricFields, - }), - collapse: { - field: 'source_node.uuid', - }, - aggs: { - nodes: { - terms: { - field: `source_node.uuid`, - include: uuidsToInclude, - size: maxBucketSize, - }, - aggs: { - by_date: { - date_histogram: { - field: 'timestamp', - min_doc_count: 0, - fixed_interval: bucketSize + 's', - }, - aggs: getMetricAggs(LISTING_METRICS_NAMES), + query: createQuery({ + type: dataset, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + filters, + metric: metricFields, + }), + collapse: { + field: 'source_node.uuid', + }, + aggs: { + nodes: { + terms: { + field: `source_node.uuid`, + include: uuidsToInclude, + size: maxBucketSize, + }, + aggs: { + by_date: { + date_histogram: { + field: 'timestamp', + min_doc_count: 0, + fixed_interval: bucketSize + 's', }, + aggs: getMetricAggs(LISTING_METRICS_NAMES), }, }, }, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], filter_path: [ 'hits.hits._source.source_node', 'hits.hits._source.service.address', diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_indices_unassigned_shard_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_indices_unassigned_shard_stats.ts index dd346cc279591..438fa536969ce 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_indices_unassigned_shard_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_indices_unassigned_shard_stats.ts @@ -45,35 +45,33 @@ async function getUnassignedShardData(req: LegacyRequest, cluster: Elasticsearch index: indexPattern, size: 0, ignore_unavailable: true, - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - clusterUuid: cluster.cluster_uuid ?? cluster.elasticsearch?.cluster?.id, - metric, - filters, - }), - aggs: { - indices: { - terms: { - field: 'shard.index', - size: maxBucketSize, - }, - aggs: { - state: { - filter: { - terms: { - 'shard.state': ['UNASSIGNED', 'INITIALIZING'], - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + clusterUuid: cluster.cluster_uuid ?? cluster.elasticsearch?.cluster?.id, + metric, + filters, + }), + aggs: { + indices: { + terms: { + field: 'shard.index', + size: maxBucketSize, + }, + aggs: { + state: { + filter: { + terms: { + 'shard.state': ['UNASSIGNED', 'INITIALIZING'], }, - aggs: { - primary: { - terms: { - field: 'shard.primary', - size: 2, - }, + }, + aggs: { + primary: { + terms: { + field: 'shard.primary', + size: 2, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_nodes_shard_count.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_nodes_shard_count.ts index c5be726403745..69de2ee52b8d8 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_nodes_shard_count.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_nodes_shard_count.ts @@ -43,22 +43,20 @@ async function getShardCountPerNode(req: LegacyRequest, cluster: ElasticsearchMo index: indexPattern, size: 0, ignore_unavailable: true, - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - clusterUuid: cluster.cluster_uuid ?? cluster.elasticsearch?.cluster?.id, - metric, - filters, - }), - aggs: { - nodes: { - terms: { - field: 'shard.node', - size: maxBucketSize, - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + clusterUuid: cluster.cluster_uuid ?? cluster.elasticsearch?.cluster?.id, + metric, + filters, + }), + aggs: { + nodes: { + terms: { + field: 'shard.node', + size: maxBucketSize, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_allocation.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_allocation.ts index 0aac81e202f0b..b307639539270 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_allocation.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_allocation.ts @@ -109,16 +109,14 @@ export function getShardAllocation( index: indexPatterns, size: config.ui.max_bucket_size, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - clusterUuid, - metric, - filters, - }), - }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + clusterUuid, + metric, + filters, + }), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); return callWithRequest(req, 'search', params).then(handleResponse); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_stats.ts index 717dc38814ae2..cfeff4e77b6de 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch/shards/get_shard_stats.ts @@ -110,19 +110,17 @@ export function getShardStats( index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query: createQuery({ - type, - dsDataset: getElasticsearchDataset(dataset), - metricset: dataset, - clusterUuid: cluster.cluster_uuid ?? cluster.elasticsearch?.cluster?.id, - metric, - filters, - }), - aggs: { - ...getShardAggs(config, includeNodes, includeIndices), - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query: createQuery({ + type, + dsDataset: getElasticsearchDataset(dataset), + metricset: dataset, + clusterUuid: cluster.cluster_uuid ?? cluster.elasticsearch?.cluster?.id, + metric, + filters, + }), + aggs: { + ...getShardAggs(config, includeNodes, includeIndices), }, }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_disabled.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_disabled.ts index 44ad2a3634188..c9352228c8758 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_disabled.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_disabled.ts @@ -10,10 +10,8 @@ import { LegacyRequest } from '../../../types'; export function setCollectionDisabled(req: LegacyRequest) { const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('admin'); const params = { - body: { - transient: { 'xpack.monitoring.elasticsearch.collection.enabled': null }, // clears the disabling method used in testing environment - persistent: { 'xpack.monitoring.elasticsearch.collection.enabled': false }, - }, + transient: { 'xpack.monitoring.elasticsearch.collection.enabled': null }, // clears the disabling method used in testing environment + persistent: { 'xpack.monitoring.elasticsearch.collection.enabled': false }, }; // https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-cluster-putsettings diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_enabled.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_enabled.ts index a09dc6bb46ce9..6ae6706b9f696 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_enabled.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_enabled.ts @@ -10,10 +10,8 @@ import { LegacyRequest } from '../../../types'; export function setCollectionEnabled(req: LegacyRequest) { const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('admin'); const params = { - body: { - transient: { 'xpack.monitoring.collection.enabled': null }, // clears the disabling method used in testing environment - persistent: { 'xpack.monitoring.collection.enabled': true }, - }, + transient: { 'xpack.monitoring.collection.enabled': null }, // clears the disabling method used in testing environment + persistent: { 'xpack.monitoring.collection.enabled': true }, }; // https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-cluster-putsettings diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_interval.ts b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_interval.ts index 873c1106f1aac..d939a02cb147b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_interval.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/elasticsearch_settings/set/collection_interval.ts @@ -10,10 +10,8 @@ import { LegacyRequest } from '../../../types'; export function setCollectionInterval(req: LegacyRequest) { const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('admin'); const params = { - body: { - transient: { 'xpack.monitoring.collection.interval': null }, // clears the disabling method used in testing environment - persistent: { 'xpack.monitoring.collection.interval': '10s' }, - }, + transient: { 'xpack.monitoring.collection.interval': null }, // clears the disabling method used in testing environment + persistent: { 'xpack.monitoring.collection.interval': '10s' }, }; // https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-cluster-putsettings diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_enterprise_search_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_enterprise_search_for_clusters.ts index 89af39c7b04e3..f9942aeb84dc2 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_enterprise_search_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_enterprise_search_for_clusters.ts @@ -51,15 +51,13 @@ export function getEnterpriseSearchForClusters( size: 0, ignore_unavailable: true, filter_path: entSearchAggFilterPath, - body: { - query: createEnterpriseSearchQuery({ - start, - end, - uuid: clusterUuid, - metric: EnterpriseSearchMetric.getMetricFields(), - }), - aggs: entSearchUuidsAgg(maxBucketSize), - }, + query: createEnterpriseSearchQuery({ + start, + end, + uuid: clusterUuid, + metric: EnterpriseSearchMetric.getMetricFields(), + }), + aggs: entSearchUuidsAgg(maxBucketSize), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_stats.ts b/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_stats.ts index 63c09d388b5de..6d9d604d62902 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/enterprise_search/get_stats.ts @@ -38,14 +38,12 @@ export async function getStats( filter_path: entSearchAggFilterPath, size: 0, ignore_unavailable: true, - body: { - query: createEnterpriseSearchQuery({ - start, - end, - uuid: clusterUuid, - }), - aggs: entSearchUuidsAgg(maxBucketSize), - }, + query: createEnterpriseSearchQuery({ + start, + end, + uuid: clusterUuid, + }), + aggs: entSearchUuidsAgg(maxBucketSize), }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibana_info.ts b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibana_info.ts index 4ab11001c8990..e4fb3b7c31184 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibana_info.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibana_info.ts @@ -62,18 +62,16 @@ export function getKibanaInfo( 'hits.hits._source.service.id', 'hits.hits._source.service.version', ], - body: { - query: createQuery({ - type, - dsDataset: getKibanaDataset(dataset), - metricset: dataset, - clusterUuid, - uuid: kibanaUuid, - metric: KibanaMetric.getMetricFields(), - }), - collapse: { field: 'kibana_stats.kibana.uuid' }, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - }, + query: createQuery({ + type, + dsDataset: getKibanaDataset(dataset), + metricset: dataset, + clusterUuid, + uuid: kibanaUuid, + metric: KibanaMetric.getMetricFields(), + }), + collapse: { field: 'kibana_stats.kibana.uuid' }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas.ts b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas.ts index 4796a340aaa4c..b0ac3f8835ff6 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas.ts @@ -67,47 +67,45 @@ export async function getKibanas(req: LegacyRequest, { clusterUuid }: { clusterU index: indexPatterns, size: config.ui.max_bucket_size, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getKibanaDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric: KibanaMetric.getMetricFields(), - }), - collapse: { - field: 'kibana_stats.kibana.uuid', - }, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - _source: [ - 'timestamp', - '@timestamp', - 'kibana_stats.process.memory.resident_set_size_in_bytes', - 'kibana.stats.process.memory.resident_set_size.bytes', - 'kibana_stats.os.load.1m', - 'kibana.stats.os.load.1m', - 'kibana_stats.response_times.average', - 'kibana.stats.response_time.avg.ms', - 'kibana_stats.response_times.max', - 'kibana.stats.response_time.max.ms', - 'kibana_stats.requests.total', - 'kibana.stats.request.total', - 'kibana_stats.kibana.transport_address', - 'kibana.stats.transport_address', - 'kibana_stats.kibana.name', - 'kibana.stats.name', - 'kibana_stats.kibana.host', - 'kibana.stats.host.name', - 'kibana_stats.kibana.uuid', - 'service.id', - 'kibana_stats.kibana.status', - 'kibana.stats.status', - 'kibana_stats.concurrent_connections', - 'kibana.stats.concurrent_connections', - ], + query: createQuery({ + type, + dsDataset: getKibanaDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric: KibanaMetric.getMetricFields(), + }), + collapse: { + field: 'kibana_stats.kibana.uuid', }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + _source: [ + 'timestamp', + '@timestamp', + 'kibana_stats.process.memory.resident_set_size_in_bytes', + 'kibana.stats.process.memory.resident_set_size.bytes', + 'kibana_stats.os.load.1m', + 'kibana.stats.os.load.1m', + 'kibana_stats.response_times.average', + 'kibana.stats.response_time.avg.ms', + 'kibana_stats.response_times.max', + 'kibana.stats.response_time.max.ms', + 'kibana_stats.requests.total', + 'kibana.stats.request.total', + 'kibana_stats.kibana.transport_address', + 'kibana.stats.transport_address', + 'kibana_stats.kibana.name', + 'kibana.stats.name', + 'kibana_stats.kibana.host', + 'kibana.stats.host.name', + 'kibana_stats.kibana.uuid', + 'service.id', + 'kibana_stats.kibana.status', + 'kibana.stats.status', + 'kibana_stats.concurrent_connections', + 'kibana.stats.concurrent_connections', + ], }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts index 82da6c42c8f4f..9f25700087b90 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts @@ -49,128 +49,126 @@ export function getKibanasForClusters(req: LegacyRequest, clusters: Cluster[], c index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getKibanaDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - aggs: { - kibana_uuids: { - terms: { - field: 'kibana_stats.kibana.uuid', - size: config.ui.max_bucket_size, - }, - aggs: { - latest_report: { - terms: { - field: 'kibana_stats.timestamp', - size: 1, - order: { - _key: 'desc', - }, + query: createQuery({ + type, + dsDataset: getKibanaDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), + aggs: { + kibana_uuids: { + terms: { + field: 'kibana_stats.kibana.uuid', + size: config.ui.max_bucket_size, + }, + aggs: { + latest_report: { + terms: { + field: 'kibana_stats.timestamp', + size: 1, + order: { + _key: 'desc', }, - aggs: { - last_seen: { - max: { - field: 'kibana_stats.timestamp', - }, + }, + aggs: { + last_seen: { + max: { + field: 'kibana_stats.timestamp', }, - response_time_max: { - max: { - field: 'kibana_stats.response_times.max', - }, + }, + response_time_max: { + max: { + field: 'kibana_stats.response_times.max', }, - memory_rss: { - max: { - field: 'kibana_stats.process.memory.resident_set_size_in_bytes', - }, + }, + memory_rss: { + max: { + field: 'kibana_stats.process.memory.resident_set_size_in_bytes', }, - memory_heap_size_limit: { - max: { - field: 'kibana_stats.process.memory.heap.size_limit', - }, + }, + memory_heap_size_limit: { + max: { + field: 'kibana_stats.process.memory.heap.size_limit', }, - concurrent_connections: { - max: { - field: 'kibana_stats.concurrent_connections', - }, + }, + concurrent_connections: { + max: { + field: 'kibana_stats.concurrent_connections', }, - requests_total: { - max: { - field: 'kibana_stats.requests.total', - }, + }, + requests_total: { + max: { + field: 'kibana_stats.requests.total', }, }, }, - response_time_max_per: { - max_bucket: { - buckets_path: 'latest_report>response_time_max', - }, + }, + response_time_max_per: { + max_bucket: { + buckets_path: 'latest_report>response_time_max', }, - memory_rss_per: { - max_bucket: { - buckets_path: 'latest_report>memory_rss', - }, + }, + memory_rss_per: { + max_bucket: { + buckets_path: 'latest_report>memory_rss', }, - memory_heap_size_limit_per: { - max_bucket: { - buckets_path: 'latest_report>memory_heap_size_limit', - }, + }, + memory_heap_size_limit_per: { + max_bucket: { + buckets_path: 'latest_report>memory_heap_size_limit', }, - concurrent_connections_per: { - max_bucket: { - buckets_path: 'latest_report>concurrent_connections', - }, + }, + concurrent_connections_per: { + max_bucket: { + buckets_path: 'latest_report>concurrent_connections', }, - requests_total_per: { - max_bucket: { - buckets_path: 'latest_report>requests_total', - }, + }, + requests_total_per: { + max_bucket: { + buckets_path: 'latest_report>requests_total', }, }, }, - response_time_max: { - max_bucket: { - buckets_path: 'kibana_uuids>response_time_max_per', - }, + }, + response_time_max: { + max_bucket: { + buckets_path: 'kibana_uuids>response_time_max_per', }, - memory_rss: { - sum_bucket: { - buckets_path: 'kibana_uuids>memory_rss_per', - }, + }, + memory_rss: { + sum_bucket: { + buckets_path: 'kibana_uuids>memory_rss_per', }, - memory_heap_size_limit: { - sum_bucket: { - buckets_path: 'kibana_uuids>memory_heap_size_limit_per', - }, + }, + memory_heap_size_limit: { + sum_bucket: { + buckets_path: 'kibana_uuids>memory_heap_size_limit_per', }, - concurrent_connections: { - sum_bucket: { - buckets_path: 'kibana_uuids>concurrent_connections_per', - }, + }, + concurrent_connections: { + sum_bucket: { + buckets_path: 'kibana_uuids>concurrent_connections_per', }, - requests_total: { - sum_bucket: { - buckets_path: 'kibana_uuids>requests_total_per', - }, + }, + requests_total: { + sum_bucket: { + buckets_path: 'kibana_uuids>requests_total_per', }, - status: { - terms: { - field: 'kibana_stats.kibana.status', - order: { - max_timestamp: 'desc', - }, + }, + status: { + terms: { + field: 'kibana_stats.kibana.status', + order: { + max_timestamp: 'desc', }, - aggs: { - max_timestamp: { - max: { - field: 'timestamp', - }, + }, + aggs: { + max_timestamp: { + max: { + field: 'timestamp', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_cluster_rule_data_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_cluster_rule_data_for_clusters.ts index 7c4ee32cde9a8..c9513352cb9b0 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_cluster_rule_data_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_cluster_rule_data_for_clusters.ts @@ -36,37 +36,35 @@ export async function getClusterRuleDataForClusters( index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getKibanaDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - aggs: { - indices: { - terms: { - field: '_index', - size: 1, - }, + query: createQuery({ + type, + dsDataset: getKibanaDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), + aggs: { + indices: { + terms: { + field: '_index', + size: 1, }, - overdue_count: { - max: { - field: 'kibana.cluster_rules.overdue.count', - }, + }, + overdue_count: { + max: { + field: 'kibana.cluster_rules.overdue.count', }, - overdue_delay_p50: { - max: { - field: 'kibana.cluster_rules.overdue.delay.p50', - }, + }, + overdue_delay_p50: { + max: { + field: 'kibana.cluster_rules.overdue.delay.p50', }, - overdue_delay_p99: { - max: { - field: 'kibana.cluster_rules.overdue.delay.p99', - }, + }, + overdue_delay_p99: { + max: { + field: 'kibana.cluster_rules.overdue.delay.p99', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_instance_rule_data_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_instance_rule_data_for_clusters.ts index 0de56533bf786..4c976a9404f2b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_instance_rule_data_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/kibana/rules/get_instance_rule_data_for_clusters.ts @@ -36,37 +36,35 @@ export async function getInstanceRuleDataForClusters( index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getKibanaDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric, - }), - aggs: { - indices: { - terms: { - field: '_index', - size: 1, - }, + query: createQuery({ + type, + dsDataset: getKibanaDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric, + }), + aggs: { + indices: { + terms: { + field: '_index', + size: 1, }, - executions: { - max: { - field: 'kibana.node_rules.executions', - }, + }, + executions: { + max: { + field: 'kibana.node_rules.executions', }, - failures: { - max: { - field: 'kibana.node_rules.failures', - }, + }, + failures: { + max: { + field: 'kibana.node_rules.failures', }, - timeouts: { - max: { - field: 'kibana.node_rules.timeouts', - }, + }, + timeouts: { + max: { + field: 'kibana.node_rules.timeouts', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_log_types.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_log_types.ts index 879069f2f565b..d612bf6f9867b 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_log_types.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_log_types.ts @@ -84,23 +84,21 @@ export async function getLogTypes( size: 0, filter_path: ['aggregations.levels.buckets', 'aggregations.types.buckets'], ignore_unavailable: true, - body: { - sort: { '@timestamp': { order: 'desc', unmapped_type: 'long' } }, - query: { - bool: { - filter: [elasticsearchLogsFilter, ...filter], - }, + sort: { '@timestamp': { order: 'desc', unmapped_type: 'long' } }, + query: { + bool: { + filter: [elasticsearchLogsFilter, ...filter], }, - aggs: { - types: { - terms: { - field: 'event.dataset', - }, - aggs: { - levels: { - terms: { - field: 'log.level', - }, + }, + aggs: { + types: { + terms: { + field: 'event.dataset', + }, + aggs: { + levels: { + terms: { + field: 'log.level', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_logs.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_logs.ts index 5d49a7b50b063..d28d09bab8eac 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_logs.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logs/get_logs.ts @@ -101,12 +101,10 @@ export async function getLogs( 'hits.hits._source.elasticsearch.node.name', ], ignore_unavailable: true, - body: { - sort: { '@timestamp': { order: 'desc', unmapped_type: 'long' } }, - query: { - bool: { - filter: [elasticsearchLogsFilter, ...filter], - }, + sort: { '@timestamp': { order: 'desc', unmapped_type: 'long' } }, + query: { + bool: { + filter: [elasticsearchLogsFilter, ...filter], }, }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_logstash_for_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_logstash_for_clusters.ts index 295f78803e678..d019c5a831721 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_logstash_for_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_logstash_for_clusters.ts @@ -64,156 +64,154 @@ export function getLogstashForClusters( index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getLogstashDataset(dataset), - metricset: dataset, - start, - end, - clusterUuid, - metric: LogstashClusterMetric.getMetricFields(), - }), - aggs: { - logstash_uuids: { - terms: { - field: 'logstash_stats.logstash.uuid', - size: maxBucketSize, - }, - aggs: { - latest_report: { - terms: { - field: 'logstash_stats.timestamp', - size: 1, - order: { - _key: 'desc', - }, + query: createQuery({ + type, + dsDataset: getLogstashDataset(dataset), + metricset: dataset, + start, + end, + clusterUuid, + metric: LogstashClusterMetric.getMetricFields(), + }), + aggs: { + logstash_uuids: { + terms: { + field: 'logstash_stats.logstash.uuid', + size: maxBucketSize, + }, + aggs: { + latest_report: { + terms: { + field: 'logstash_stats.timestamp', + size: 1, + order: { + _key: 'desc', }, - aggs: { - memory_used: { - max: { - field: 'logstash_stats.jvm.mem.heap_used_in_bytes', - }, + }, + aggs: { + memory_used: { + max: { + field: 'logstash_stats.jvm.mem.heap_used_in_bytes', }, - memory: { - max: { - field: 'logstash_stats.jvm.mem.heap_max_in_bytes', - }, + }, + memory: { + max: { + field: 'logstash_stats.jvm.mem.heap_max_in_bytes', }, - events_in_total: { - max: { - field: 'logstash_stats.events.in', - }, + }, + events_in_total: { + max: { + field: 'logstash_stats.events.in', }, - events_out_total: { - max: { - field: 'logstash_stats.events.out', - }, + }, + events_out_total: { + max: { + field: 'logstash_stats.events.out', }, }, }, - memory_used_per_node: { - max_bucket: { - buckets_path: 'latest_report>memory_used', - }, + }, + memory_used_per_node: { + max_bucket: { + buckets_path: 'latest_report>memory_used', }, - memory_per_node: { - max_bucket: { - buckets_path: 'latest_report>memory', - }, + }, + memory_per_node: { + max_bucket: { + buckets_path: 'latest_report>memory', }, - events_in_total_per_node: { - max_bucket: { - buckets_path: 'latest_report>events_in_total', - }, + }, + events_in_total_per_node: { + max_bucket: { + buckets_path: 'latest_report>events_in_total', }, - events_out_total_per_node: { - max_bucket: { - buckets_path: 'latest_report>events_out_total', - }, + }, + events_out_total_per_node: { + max_bucket: { + buckets_path: 'latest_report>events_out_total', }, }, }, - logstash_versions: { - terms: { - field: 'logstash_stats.logstash.version', - size: maxBucketSize, - }, + }, + logstash_versions: { + terms: { + field: 'logstash_stats.logstash.version', + size: maxBucketSize, + }, + }, + pipelines_nested: { + nested: { + path: 'logstash_stats.pipelines', }, - pipelines_nested: { - nested: { - path: 'logstash_stats.pipelines', + aggs: { + pipelines: { + sum_bucket: { + buckets_path: 'queue_types>num_pipelines', + }, }, - aggs: { - pipelines: { - sum_bucket: { - buckets_path: 'queue_types>num_pipelines', - }, + queue_types: { + terms: { + field: 'logstash_stats.pipelines.queue.type', + size: maxBucketSize, }, - queue_types: { - terms: { - field: 'logstash_stats.pipelines.queue.type', - size: maxBucketSize, - }, - aggs: { - num_pipelines: { - cardinality: { - field: 'logstash_stats.pipelines.id', - }, + aggs: { + num_pipelines: { + cardinality: { + field: 'logstash_stats.pipelines.id', }, }, }, }, }, - pipelines_nested_mb: { - nested: { - path: 'logstash.node.stats.pipelines', + }, + pipelines_nested_mb: { + nested: { + path: 'logstash.node.stats.pipelines', + }, + aggs: { + pipelines: { + sum_bucket: { + buckets_path: 'queue_types>num_pipelines', + }, }, - aggs: { - pipelines: { - sum_bucket: { - buckets_path: 'queue_types>num_pipelines', - }, + queue_types: { + terms: { + field: 'logstash.node.stats.pipelines.queue.type', + size: maxBucketSize, }, - queue_types: { - terms: { - field: 'logstash.node.stats.pipelines.queue.type', - size: maxBucketSize, - }, - aggs: { - num_pipelines: { - cardinality: { - field: 'logstash.node.stats.pipelines.id', - }, + aggs: { + num_pipelines: { + cardinality: { + field: 'logstash.node.stats.pipelines.id', }, }, }, }, }, - events_in_total: { - sum_bucket: { - buckets_path: 'logstash_uuids>events_in_total_per_node', - }, + }, + events_in_total: { + sum_bucket: { + buckets_path: 'logstash_uuids>events_in_total_per_node', }, - events_out_total: { - sum_bucket: { - buckets_path: 'logstash_uuids>events_out_total_per_node', - }, + }, + events_out_total: { + sum_bucket: { + buckets_path: 'logstash_uuids>events_out_total_per_node', }, - memory_used: { - sum_bucket: { - buckets_path: 'logstash_uuids>memory_used_per_node', - }, + }, + memory_used: { + sum_bucket: { + buckets_path: 'logstash_uuids>memory_used_per_node', }, - memory: { - sum_bucket: { - buckets_path: 'logstash_uuids>memory_per_node', - }, + }, + memory: { + sum_bucket: { + buckets_path: 'logstash_uuids>memory_per_node', }, - max_uptime: { - max: { - field: 'logstash_stats.jvm.uptime_in_millis', - }, + }, + max_uptime: { + max: { + field: 'logstash_stats.jvm.uptime_in_millis', }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.test.ts index 356dbfaa29d41..10e16fa12e7cc 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.test.ts @@ -224,8 +224,6 @@ describe('get_logstash_info', () => { }); expect(callWithRequest.mock.calls.length).toBe(1); expect(callWithRequest.mock.calls[0].length).toBe(3); - expect(callWithRequest.mock.calls[0][2].body.query.bool.filter[0]).toBe( - standaloneClusterFilter - ); + expect(callWithRequest.mock.calls[0][2].query.bool.filter[0]).toBe(standaloneClusterFilter); }); }); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.ts index 347085f162e7b..228054dbfd797 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_node_info.ts @@ -70,15 +70,13 @@ export function getNodeInfo( 'hits.hits._source.logstash_stats.timestamp', 'hits.hits._source.logstash.node.stats.timestamp', ], - body: { - query: { - bool: { - filter: [clusterFilter, { term: { 'logstash_stats.logstash.uuid': logstashUuid } }], - }, + query: { + bool: { + filter: [clusterFilter, { term: { 'logstash_stats.logstash.uuid': logstashUuid } }], }, - collapse: { field: 'logstash_stats.logstash.uuid' }, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], }, + collapse: { field: 'logstash_stats.logstash.uuid' }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.test.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.test.ts index 3483d9be5d4a8..8b88f51ad37a6 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.test.ts @@ -53,7 +53,7 @@ describe('getNodes', () => { expect(callWithRequest.mock.calls.length).toBe(1); expect(callWithRequest.mock.calls[0].length).toBe(3); - const filters = callWithRequest.mock.calls[0][2].body.query.bool.filter; + const filters = callWithRequest.mock.calls[0][2].query.bool.filter; expect(filters).toContainEqual( expect.objectContaining({ exists: { diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.ts index a153b43fb26c3..d97cd7b2fd955 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_nodes.ts @@ -87,50 +87,48 @@ export async function getNodes(req: LegacyRequest, { clusterUuid }: { clusterUui index: indexPatterns, size: config.ui.max_bucket_size, ignore_unavailable: true, - body: { - query: createQuery({ - type, - dsDataset: getLogstashDataset(dataset), - metricset: dataset, - filters, - start, - end, - clusterUuid, - metric: LogstashMetric.getMetricFields(), - }), - collapse: { - field: 'logstash_stats.logstash.uuid', - }, - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - _source: [ - 'timestamp', - '@timestamp', - 'logstash_stats.process.cpu.percent', - 'logstash.node.stats.process.cpu.percent', - 'logstash_stats.jvm.mem.heap_used_percent', - 'logstash.node.stats.jvm.mem.heap_used_percent', - 'logstash_stats.os.cpu.load_average.1m', - 'logstash.node.stats.os.cpu.load_average.1m', - 'logstash_stats.events.out', - 'logstash.node.stats.events.out', - 'logstash_stats.logstash.http_address', - 'logstash.node.stats.logstash.http_address', - 'logstash_stats.logstash.name', - 'logstash.node.stats.logstash.name', - 'logstash_stats.logstash.host', - 'logstash.node.stats.logstash.host', - 'logstash_stats.logstash.uuid', - 'logstash.node.stats.logstash.uuid', - 'logstash_stats.logstash.status', - 'logstash.node.stats.logstash.status', - 'logstash_stats.logstash.pipeline', - 'logstash.node.stats.logstash.pipeline', - 'logstash_stats.reloads', - 'logstash.node.stats.reloads', - 'logstash_stats.logstash.version', - 'logstash.node.stats.logstash.version', - ], + query: createQuery({ + type, + dsDataset: getLogstashDataset(dataset), + metricset: dataset, + filters, + start, + end, + clusterUuid, + metric: LogstashMetric.getMetricFields(), + }), + collapse: { + field: 'logstash_stats.logstash.uuid', }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + _source: [ + 'timestamp', + '@timestamp', + 'logstash_stats.process.cpu.percent', + 'logstash.node.stats.process.cpu.percent', + 'logstash_stats.jvm.mem.heap_used_percent', + 'logstash.node.stats.jvm.mem.heap_used_percent', + 'logstash_stats.os.cpu.load_average.1m', + 'logstash.node.stats.os.cpu.load_average.1m', + 'logstash_stats.events.out', + 'logstash.node.stats.events.out', + 'logstash_stats.logstash.http_address', + 'logstash.node.stats.logstash.http_address', + 'logstash_stats.logstash.name', + 'logstash.node.stats.logstash.name', + 'logstash_stats.logstash.host', + 'logstash.node.stats.logstash.host', + 'logstash_stats.logstash.uuid', + 'logstash.node.stats.logstash.uuid', + 'logstash_stats.logstash.status', + 'logstash.node.stats.logstash.status', + 'logstash_stats.logstash.pipeline', + 'logstash.node.stats.logstash.pipeline', + 'logstash_stats.reloads', + 'logstash.node.stats.reloads', + 'logstash_stats.logstash.version', + 'logstash.node.stats.logstash.version', + ], }; const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_ids.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_ids.ts index 348b1c1bb61cd..125af752b2e8f 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_ids.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_ids.ts @@ -49,34 +49,32 @@ export async function getLogstashPipelineIds({ size: 0, ignore_unavailable: true, filter_path: ['aggregations.nest.id.buckets', 'aggregations.nest_mb.id.buckets'], - body: { - query: createQuery({ - start, - end, - metric: LogstashMetric.getMetricFields(), - clusterUuid, - filters, - }), - aggs: { - nest: { - nested: { - path: 'logstash_stats.pipelines', - }, - aggs: { - id: { - terms: { - field: 'logstash_stats.pipelines.id', - size, - }, - aggs: { - unnest: { - reverse_nested: {}, - aggs: { - nodes: { - terms: { - field: 'logstash_stats.logstash.uuid', - size, - }, + query: createQuery({ + start, + end, + metric: LogstashMetric.getMetricFields(), + clusterUuid, + filters, + }), + aggs: { + nest: { + nested: { + path: 'logstash_stats.pipelines', + }, + aggs: { + id: { + terms: { + field: 'logstash_stats.pipelines.id', + size, + }, + aggs: { + unnest: { + reverse_nested: {}, + aggs: { + nodes: { + terms: { + field: 'logstash_stats.logstash.uuid', + size, }, }, }, @@ -84,25 +82,25 @@ export async function getLogstashPipelineIds({ }, }, }, - nest_mb: { - nested: { - path: 'logstash.node.stats.pipelines', - }, - aggs: { - id: { - terms: { - field: 'logstash.node.stats.pipelines.id', - size, - }, - aggs: { - unnest_mb: { - reverse_nested: {}, - aggs: { - nodes: { - terms: { - field: 'logstash.node.stats.logstash.uuid', - size, - }, + }, + nest_mb: { + nested: { + path: 'logstash.node.stats.pipelines', + }, + aggs: { + id: { + terms: { + field: 'logstash.node.stats.pipelines.id', + size, + }, + aggs: { + unnest_mb: { + reverse_nested: {}, + aggs: { + nodes: { + terms: { + field: 'logstash.node.stats.logstash.uuid', + size, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_state_document.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_state_document.ts index 01aa42e79873a..383411ae6358c 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_state_document.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_state_document.ts @@ -56,12 +56,10 @@ export async function getPipelineStateDocument({ index: indexPatterns, size: 1, ignore_unavailable: true, - body: { - _source: { excludes: 'logstash_state.pipeline.representation.plugins' }, - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query, - terminate_after: 1, // Safe to do because all these documents are functionally identical - }, + _source: { excludes: 'logstash_state.pipeline.representation.plugins' }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query, + terminate_after: 1, // Safe to do because all these documents are functionally identical }; const resp = (await callWithRequest(req, 'search', params)) as ElasticsearchResponse; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_stats_aggregation.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_stats_aggregation.ts index a76eb3b870317..831bf0c291901 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_stats_aggregation.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_stats_aggregation.ts @@ -148,12 +148,10 @@ function fetchPipelineLatestStats( 'aggregations.pipelines_mb.scoped.vertices.vertex_id.buckets.duration_in_millis_total', 'aggregations.pipelines_mb.scoped.total_processor_duration_stats', ], - body: { - query, - aggs: { - pipelines: pipelineAggregation('logstash_stats'), - pipelines_mb: pipelineAggregation('logstash.node.stats'), - }, + query, + aggs: { + pipelines: pipelineAggregation('logstash_stats'), + pipelines_mb: pipelineAggregation('logstash.node.stats'), }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_versions.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_versions.ts index ceddc6ec46951..3f0791f6474bb 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_versions.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_versions.ts @@ -136,11 +136,9 @@ function fetchPipelineVersions({ index: indexPatterns, size: 0, ignore_unavailable: true, - body: { - sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, - query, - aggs, - }, + sort: { timestamp: { order: 'desc', unmapped_type: 'long' } }, + query, + aggs, }; return callWithRequest(req, 'search', params); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts index 6b2758392ac69..5ada7127a9829 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts @@ -201,10 +201,8 @@ function fetchPipelineVertexTimeSeriesStats({ 'aggregations.timeseries.buckets.pipelines_mb.scoped.vertices.vertex_id.queue_push_duration_in_millis_total', 'aggregations.timeseries.buckets.pipelines_mb.scoped.total_processor_duration_stats', ], - body: { - query, - aggs, - }, + query, + aggs, }; return callWithRequest(req, 'search', params); diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/setup/collection/get_collection_status.ts b/x-pack/platform/plugins/private/monitoring/server/lib/setup/collection/get_collection_status.ts index 41313bfb347a2..5cd45da03d472 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/setup/collection/get_collection_status.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/setup/collection/get_collection_status.ts @@ -76,133 +76,131 @@ const getRecentMonitoringDocuments = async ( size: 0, ignore_unavailable: true, filter_path: ['aggregations.indices.buckets'], - body: { - query: { - bool: { - filter: filters, - ...nodesClause, - }, + query: { + bool: { + filter: filters, + ...nodesClause, }, - aggs: { - indices: { - terms: { - field: '_index', - size: 50, - }, - aggs: { - es_uuids: { - terms: { - field: 'node_stats.node_id', - size, - }, - aggs: { - single_type: { - filter: { - bool: { - should: [ - { term: { type: 'node_stats' } }, - { term: { 'metricset.name': 'node_stats' } }, - ], - }, + }, + aggs: { + indices: { + terms: { + field: '_index', + size: 50, + }, + aggs: { + es_uuids: { + terms: { + field: 'node_stats.node_id', + size, + }, + aggs: { + single_type: { + filter: { + bool: { + should: [ + { term: { type: 'node_stats' } }, + { term: { 'metricset.name': 'node_stats' } }, + ], }, - aggs: { - by_timestamp: { - max: { - field: 'timestamp', - }, + }, + aggs: { + by_timestamp: { + max: { + field: 'timestamp', }, }, }, }, }, - kibana_uuids: { - terms: { - field: 'kibana_stats.kibana.uuid', - size, - }, - aggs: { - single_type: { - filter: { - bool: { - should: [ - { term: { type: 'kibana_stats' } }, - { term: { 'metricset.name': 'stats' } }, - ], - }, + }, + kibana_uuids: { + terms: { + field: 'kibana_stats.kibana.uuid', + size, + }, + aggs: { + single_type: { + filter: { + bool: { + should: [ + { term: { type: 'kibana_stats' } }, + { term: { 'metricset.name': 'stats' } }, + ], }, - aggs: { - by_timestamp: { - max: { - field: 'timestamp', - }, + }, + aggs: { + by_timestamp: { + max: { + field: 'timestamp', }, }, }, }, }, - beats_uuids: { - terms: { - field: 'beats_stats.beat.uuid', - size, - }, - aggs: { - single_type: { - filter: { - bool: { - should: [ - { term: { type: 'beats_stats' } }, - { term: { 'metricset.name': 'beats_stats' } }, - ], - }, + }, + beats_uuids: { + terms: { + field: 'beats_stats.beat.uuid', + size, + }, + aggs: { + single_type: { + filter: { + bool: { + should: [ + { term: { type: 'beats_stats' } }, + { term: { 'metricset.name': 'beats_stats' } }, + ], }, - aggs: { - by_timestamp: { - max: { - field: 'timestamp', - }, + }, + aggs: { + by_timestamp: { + max: { + field: 'timestamp', }, - beat_type: { - terms: { - field: 'beats_stats.beat.type', - size, - }, + }, + beat_type: { + terms: { + field: 'beats_stats.beat.type', + size, }, - cluster_uuid: { - terms: { - field: 'cluster_uuid', - size, - }, + }, + cluster_uuid: { + terms: { + field: 'cluster_uuid', + size, }, }, }, }, }, - logstash_uuids: { - terms: { - field: 'logstash_stats.logstash.uuid', - size, - }, - aggs: { - single_type: { - filter: { - bool: { - should: [ - { term: { type: 'logstash_stats' } }, - { term: { 'metricset.name': 'stats' } }, - ], - }, + }, + logstash_uuids: { + terms: { + field: 'logstash_stats.logstash.uuid', + size, + }, + aggs: { + single_type: { + filter: { + bool: { + should: [ + { term: { type: 'logstash_stats' } }, + { term: { 'metricset.name': 'stats' } }, + ], }, - aggs: { - by_timestamp: { - max: { - field: 'timestamp', - }, + }, + aggs: { + by_timestamp: { + max: { + field: 'timestamp', }, - cluster_uuid: { - terms: { - field: 'cluster_uuid', - size, - }, + }, + cluster_uuid: { + terms: { + field: 'cluster_uuid', + size, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/lib/standalone_clusters/has_standalone_clusters.ts b/x-pack/platform/plugins/private/monitoring/server/lib/standalone_clusters/has_standalone_clusters.ts index d9ec794dd7606..c6e302c8c820c 100644 --- a/x-pack/platform/plugins/private/monitoring/server/lib/standalone_clusters/has_standalone_clusters.ts +++ b/x-pack/platform/plugins/private/monitoring/server/lib/standalone_clusters/has_standalone_clusters.ts @@ -86,13 +86,11 @@ export async function hasStandaloneClusters(req: LegacyRequest, ccs: string) { const params = { index: indexPatternList, - body: { - size: 0, - terminate_after: 1, - query: { - bool: { - filter: filters, - }, + size: 0, + terminate_after: 1, + query: { + bool: { + filter: filters, }, }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr.ts b/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr.ts index 03f9fff6bc943..b2fdd8683f6d5 100644 --- a/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr.ts +++ b/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr.ts @@ -128,96 +128,94 @@ function buildRequest({ clusterUuid, config, esIndexPattern, timeRange }: BuildR 'aggregations.by_follower_index.buckets.by_shard_id.buckets.leader_lag_ops.value', 'aggregations.by_follower_index.buckets.by_shard_id.buckets.follower_lag_ops.value', ], - body: { - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - query: { - bool: { - must: [ - { - term: { - cluster_uuid: { - value: clusterUuid, - }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + query: { + bool: { + must: [ + { + term: { + cluster_uuid: { + value: clusterUuid, }, }, - { - bool: { - should: [ - { - term: { - type: { - value: 'ccr_stats', - }, + }, + { + bool: { + should: [ + { + term: { + type: { + value: 'ccr_stats', }, }, - { - term: { - 'metricset.name': { - value: 'ccr', - }, + }, + { + term: { + 'metricset.name': { + value: 'ccr', }, }, - { - term: { - 'data_stream.dataset': { - value: getElasticsearchDataset('ccr'), - }, + }, + { + term: { + 'data_stream.dataset': { + value: getElasticsearchDataset('ccr'), }, }, - ], - }, - }, - { - range: { - timestamp: { - format: 'epoch_millis', - gte: min, - lte: max, }, + ], + }, + }, + { + range: { + timestamp: { + format: 'epoch_millis', + gte: min, + lte: max, }, }, - ], + }, + ], + }, + }, + collapse: { + field: 'ccr_stats.follower_index', + inner_hits: { + name: 'by_shard', + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + size: maxBucketSize, + collapse: { + field: 'ccr_stats.shard_id', }, }, - collapse: { - field: 'ccr_stats.follower_index', - inner_hits: { - name: 'by_shard', - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + }, + aggs: { + by_follower_index: { + terms: { + field: 'ccr_stats.follower_index', size: maxBucketSize, - collapse: { - field: 'ccr_stats.shard_id', - }, }, - }, - aggs: { - by_follower_index: { - terms: { - field: 'ccr_stats.follower_index', - size: maxBucketSize, - }, - aggs: { - leader_index: { - terms: { - field: 'ccr_stats.leader_index', - size: 1, - }, - aggs: { - remote_cluster: { - terms: { - field: 'ccr_stats.remote_cluster', - size: 1, - }, + aggs: { + leader_index: { + terms: { + field: 'ccr_stats.leader_index', + size: 1, + }, + aggs: { + remote_cluster: { + terms: { + field: 'ccr_stats.remote_cluster', + size: 1, }, }, }, - by_shard_id: { - terms: { - field: 'ccr_stats.shard_id', - size: 10, - }, - aggs, + }, + by_shard_id: { + terms: { + field: 'ccr_stats.shard_id', + size: 10, }, + aggs, }, }, }, diff --git a/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr_shard.ts b/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr_shard.ts index b02ba1e455bce..7f0173c569b92 100644 --- a/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr_shard.ts +++ b/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch/ccr_shard.ts @@ -52,31 +52,29 @@ async function getCcrStat( 'hits.hits.inner_hits.oldest.hits.hits._source.ccr_stats.failed_read_requests', 'hits.hits.inner_hits.oldest.hits.hits._source.elasticsearch.ccr.requests.failed.read.count', ], - body: { - sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], - query: { - bool: { - must: [ - ...filters, - { - range: { - timestamp: { - format: 'epoch_millis', - gte: min, - lte: max, - }, + sort: [{ timestamp: { order: 'desc', unmapped_type: 'long' } }], + query: { + bool: { + must: [ + ...filters, + { + range: { + timestamp: { + format: 'epoch_millis', + gte: min, + lte: max, }, }, - ], - }, + }, + ], }, - collapse: { - field: 'ccr_stats.follower_index', - inner_hits: { - name: 'oldest', - size: 1, - sort: [{ timestamp: { order: 'asc', unmapped_type: 'long' } }], - }, + }, + collapse: { + field: 'ccr_stats.follower_index', + inner_hits: { + name: 'oldest', + size: 1, + sort: [{ timestamp: { order: 'asc', unmapped_type: 'long' } }], }, }, }; diff --git a/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts b/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts index 824efa62e7a26..9c9f06d867237 100644 --- a/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts +++ b/x-pack/platform/plugins/private/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { RequestHandlerContext } from '@kbn/core/server'; import { prefixIndexPatternWithCcs } from '../../../../../../common/ccs_utils'; import { @@ -50,8 +50,8 @@ const checkLatestMonitoringIsLegacy = async (context: RequestHandlerContext, ind const client = (await context.core).elasticsearch.client.asCurrentUser; const result = await client.search>({ index, - body: queryBody, - } as estypes.SearchRequest); + ...queryBody, + }); const { aggregations } = result; const counts = { diff --git a/x-pack/platform/plugins/private/monitoring/server/static_globals.ts b/x-pack/platform/plugins/private/monitoring/server/static_globals.ts index 2bcacb5c45a9a..096953d21ffac 100644 --- a/x-pack/platform/plugins/private/monitoring/server/static_globals.ts +++ b/x-pack/platform/plugins/private/monitoring/server/static_globals.ts @@ -6,7 +6,7 @@ */ import { CoreSetup, ElasticsearchClient, Logger, PluginInitializerContext } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { MonitoringConfig } from './config'; import { PluginsSetup } from './types'; import { mbSafeQuery } from './lib/mb_safe_query'; diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_beats_stats.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_beats_stats.ts index 109b1485f8a40..837fce0cd60e8 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_beats_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_beats_stats.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { createQuery } from './create_query'; import { INDEX_PATTERN_BEATS } from '../../common/constants'; diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_cluster_uuids.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_cluster_uuids.ts index ffd4c7dbe49f8..f32f4981ef750 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_cluster_uuids.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_cluster_uuids.ts @@ -8,7 +8,7 @@ import { get } from 'lodash'; import moment from 'moment'; import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { createQuery } from './create_query'; import { INDEX_PATTERN_ELASTICSEARCH, diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_es_stats.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_es_stats.ts index ba977d78a3f2e..890bb396a65f5 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_es_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_es_stats.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import moment from 'moment'; import { INDEX_PATTERN_ELASTICSEARCH } from '../../common/constants'; diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_high_level_stats.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_high_level_stats.ts index 0f9aa4647d036..1ee99fb15e7c1 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_high_level_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_high_level_stats.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { createQuery } from './create_query'; import { INDEX_PATTERN_KIBANA, diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.test.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.test.ts index 35480cc6b5c98..cd037fa062ed8 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.test.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { getUsageStats, combineStats, diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.ts index 6ac30711aff58..f86445324bc21 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_kibana_stats.ts @@ -7,7 +7,7 @@ import moment from 'moment'; import { isEmpty } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient } from '@kbn/core/server'; import { KIBANA_SYSTEM_ID, TELEMETRY_COLLECTION_INTERVAL } from '../../common/constants'; import { diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_licenses.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_licenses.ts index 9a3d1f41cec5e..350404db7fa36 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_licenses.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/get_licenses.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { LicenseGetLicenseInformation } from '@elastic/elasticsearch/lib/api/types'; import { INDEX_PATTERN_ELASTICSEARCH, USAGE_FETCH_INTERVAL } from '../../common/constants'; diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_agent_monitoring.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_agent_monitoring.ts index d80eb0fcee832..b8cea092abd56 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_agent_monitoring.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_agent_monitoring.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import moment from 'moment'; import { createQuery } from './create_query'; import { mapToList } from './get_high_level_stats'; diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_metricbeat_monitoring.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_metricbeat_monitoring.ts index b3b1f9910a559..a24e9fd64bcfd 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_metricbeat_monitoring.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_metricbeat_monitoring.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { createQuery } from './create_query'; import { mapToList } from './get_high_level_stats'; import { incrementByKey } from './get_high_level_stats'; diff --git a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_self_monitoring.ts b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_self_monitoring.ts index 9fb35c948e705..159638107eb13 100644 --- a/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_self_monitoring.ts +++ b/x-pack/platform/plugins/private/monitoring/server/telemetry_collection/logstash_self_monitoring.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { createQuery } from './create_query'; import { mapToList } from './get_high_level_stats'; import { incrementByKey } from './get_high_level_stats'; diff --git a/x-pack/platform/plugins/private/painless_lab/server/routes/api/execute.ts b/x-pack/platform/plugins/private/painless_lab/server/routes/api/execute.ts index 43ee24af223ce..57939d352efe8 100644 --- a/x-pack/platform/plugins/private/painless_lab/server/routes/api/execute.ts +++ b/x-pack/platform/plugins/private/painless_lab/server/routes/api/execute.ts @@ -34,7 +34,7 @@ export function registerExecuteRoute({ router, license }: RouteDependencies) { const client = (await ctx.core).elasticsearch.client.asCurrentUser; const response = await client.scriptsPainlessExecute( { - // @ts-expect-error `ExecutePainlessScriptRequest.body` does not allow `string` + // Should this be `script` instead? body, }, { diff --git a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.test.ts b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.test.ts index e2805b6616127..c9c4724fe0ff6 100644 --- a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.test.ts +++ b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.test.ts @@ -115,16 +115,14 @@ describe('ADD remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - seeds: ['127.0.0.1:9300'], - skip_unavailable: false, - mode: 'sniff', - node_connections: null, - }, + persistent: { + cluster: { + remote: { + test: { + seeds: ['127.0.0.1:9300'], + skip_unavailable: false, + mode: 'sniff', + node_connections: null, }, }, }, @@ -173,17 +171,15 @@ describe('ADD remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - skip_unavailable: false, - mode: 'proxy', - proxy_address: '127.0.0.1:9300', - proxy_socket_connections: null, - server_name: 'foobar', - }, + persistent: { + cluster: { + remote: { + test: { + skip_unavailable: false, + mode: 'proxy', + proxy_address: '127.0.0.1:9300', + proxy_socket_connections: null, + server_name: 'foobar', }, }, }, @@ -242,16 +238,14 @@ describe('ADD remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - seeds: ['127.0.0.1:9300'], - skip_unavailable: false, - mode: 'sniff', - node_connections: null, - }, + persistent: { + cluster: { + remote: { + test: { + seeds: ['127.0.0.1:9300'], + skip_unavailable: false, + mode: 'sniff', + node_connections: null, }, }, }, diff --git a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.ts b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.ts index aa690fc935470..0751ade44808b 100644 --- a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.ts +++ b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/add_route.ts @@ -61,9 +61,9 @@ export const register = (deps: RouteDependencies): void => { } const addClusterPayload = serializeCluster(request.body as Cluster); - const updateClusterResponse = await clusterClient.asCurrentUser.cluster.putSettings({ - body: addClusterPayload, - }); + const updateClusterResponse = await clusterClient.asCurrentUser.cluster.putSettings( + addClusterPayload + ); const acknowledged = get(updateClusterResponse, 'acknowledged'); const cluster = get(updateClusterResponse, `persistent.cluster.remote.${name}`); diff --git a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.test.ts b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.test.ts index ed92c78f9d09d..e2a9ab7a87a27 100644 --- a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.test.ts +++ b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.test.ts @@ -132,19 +132,17 @@ describe('DELETE remote clusters', () => { expect(getSettingsMockFn).toHaveBeenCalledWith(); expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - seeds: null, - skip_unavailable: null, - mode: null, - proxy_address: null, - proxy_socket_connections: null, - server_name: null, - node_connections: null, - }, + persistent: { + cluster: { + remote: { + test: { + seeds: null, + skip_unavailable: null, + mode: null, + proxy_address: null, + proxy_socket_connections: null, + server_name: null, + node_connections: null, }, }, }, @@ -279,19 +277,17 @@ describe('DELETE remote clusters', () => { expect(getSettingsMockFn).toHaveBeenCalledWith(); expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - seeds: null, - skip_unavailable: null, - mode: null, - node_connections: null, - proxy_address: null, - proxy_socket_connections: null, - server_name: null, - }, + persistent: { + cluster: { + remote: { + test: { + seeds: null, + skip_unavailable: null, + mode: null, + node_connections: null, + proxy_address: null, + proxy_socket_connections: null, + server_name: null, }, }, }, diff --git a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.ts b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.ts index b99748569c63e..3ff17780cf6dd 100644 --- a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.ts +++ b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/delete_route.ts @@ -74,9 +74,7 @@ export const register = (deps: RouteDependencies): void => { try { const body = serializeCluster({ name, hasDeprecatedProxySetting }, undefined, true); - const updateClusterResponse = await clusterClient.asCurrentUser.cluster.putSettings({ - body, - }); + const updateClusterResponse = await clusterClient.asCurrentUser.cluster.putSettings(body); const acknowledged = get(updateClusterResponse, 'acknowledged'); const cluster = get(updateClusterResponse, `persistent.cluster.remote.${name}`); diff --git a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.test.ts b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.test.ts index 52344d21ae1db..757841bf5d00a 100644 --- a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.test.ts +++ b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.test.ts @@ -132,16 +132,14 @@ describe('UPDATE remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - seeds: ['127.0.0.1:9300'], - skip_unavailable: true, - mode: 'sniff', - node_connections: null, - }, + persistent: { + cluster: { + remote: { + test: { + seeds: ['127.0.0.1:9300'], + skip_unavailable: true, + mode: 'sniff', + node_connections: null, }, }, }, @@ -207,19 +205,17 @@ describe('UPDATE remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - proxy_address: '127.0.0.1:9300', - skip_unavailable: true, - mode: 'proxy', - proxy_socket_connections: 18, - node_connections: null, - seeds: null, - server_name: null, - }, + persistent: { + cluster: { + remote: { + test: { + proxy_address: '127.0.0.1:9300', + skip_unavailable: true, + mode: 'proxy', + proxy_socket_connections: 18, + node_connections: null, + seeds: null, + server_name: null, }, }, }, @@ -287,18 +283,16 @@ describe('UPDATE remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - proxy_address: '127.0.0.1:9300', - skip_unavailable: true, - mode: 'proxy', - proxy_socket_connections: 18, - server_name: null, - proxy: null, - }, + persistent: { + cluster: { + remote: { + test: { + proxy_address: '127.0.0.1:9300', + skip_unavailable: true, + mode: 'proxy', + proxy_socket_connections: 18, + server_name: null, + proxy: null, }, }, }, @@ -365,16 +359,14 @@ describe('UPDATE remote clusters', () => { expect(remoteInfoMockFn).toHaveBeenCalledWith(); expect(putSettingsMockFn).toHaveBeenCalledWith({ - body: { - persistent: { - cluster: { - remote: { - test: { - seeds: ['127.0.0.1:9300'], - skip_unavailable: false, - mode: 'sniff', - node_connections: null, - }, + persistent: { + cluster: { + remote: { + test: { + seeds: ['127.0.0.1:9300'], + skip_unavailable: false, + mode: 'sniff', + node_connections: null, }, }, }, diff --git a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.ts b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.ts index 8149cadc6b32a..172115e1c3e3c 100644 --- a/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.ts +++ b/x-pack/platform/plugins/private/remote_clusters/server/routes/api/update_route.ts @@ -74,9 +74,9 @@ export const register = (deps: RouteDependencies): void => { previousClusterConfig[name].mode ); - const updateClusterResponse = await clusterClient.asCurrentUser.cluster.putSettings({ - body: updateClusterPayload, - }); + const updateClusterResponse = await clusterClient.asCurrentUser.cluster.putSettings( + updateClusterPayload + ); const acknowledged = get(updateClusterResponse, 'acknowledged'); const cluster = get( diff --git a/x-pack/platform/plugins/private/reporting/server/lib/content_stream.test.ts b/x-pack/platform/plugins/private/reporting/server/lib/content_stream.test.ts index 91ab3953aa8a9..46eddff5dd464 100644 --- a/x-pack/platform/plugins/private/reporting/server/lib/content_stream.test.ts +++ b/x-pack/platform/plugins/private/reporting/server/lib/content_stream.test.ts @@ -58,7 +58,7 @@ describe('ContentStream', () => { const [[request]] = client.search.mock.calls; expect(request).toHaveProperty('index', 'somewhere'); expect(request).toHaveProperty( - 'body.query.constant_score.filter.bool.must.0.term._id', + 'query.constant_score.filter.bool.must.0.term._id', 'something' ); }); @@ -124,17 +124,17 @@ describe('ContentStream', () => { const [[request1], [request2], [request3]] = client.search.mock.calls; expect(request1).toHaveProperty( - 'body.query.constant_score.filter.bool.must.0.term._id', + 'query.constant_score.filter.bool.must.0.term._id', 'something' ); expect(request2).toHaveProperty('index', '.reporting-*,.kibana-reporting*'); expect(request2).toHaveProperty( - 'body.query.constant_score.filter.bool.must.0.term.parent_id', + 'query.constant_score.filter.bool.must.0.term.parent_id', 'something' ); expect(request3).toHaveProperty('index', '.reporting-*,.kibana-reporting*'); expect(request3).toHaveProperty( - 'body.query.constant_score.filter.bool.must.0.term.parent_id', + 'query.constant_score.filter.bool.must.0.term.parent_id', 'something' ); }); @@ -224,7 +224,7 @@ describe('ContentStream', () => { expect(request).toHaveProperty('id', 'something'); expect(request).toHaveProperty('index', 'somewhere'); - expect(request).toHaveProperty('body.doc.output.content', '123456'); + expect(request).toHaveProperty('doc.output.content', '123456'); }); it('should update a number of written bytes', async () => { @@ -266,10 +266,7 @@ describe('ContentStream', () => { const [[request]] = client.update.mock.calls; - expect(request).toHaveProperty( - 'body.doc.output.content', - Buffer.from('12345').toString('base64') - ); + expect(request).toHaveProperty('doc.output.content', Buffer.from('12345').toString('base64')); }); it('should remove all previous chunks before writing', async () => { @@ -281,7 +278,7 @@ describe('ContentStream', () => { const [[request]] = client.deleteByQuery.mock.calls; expect(request).toHaveProperty('index', 'somewhere'); - expect(request).toHaveProperty('body.query.match.parent_id', 'something'); + expect(request).toHaveProperty('query.match.parent_id', 'something'); }); it('should split raw data into chunks', async () => { @@ -291,7 +288,7 @@ describe('ContentStream', () => { expect(client.update).toHaveBeenCalledTimes(1); expect(client.update).toHaveBeenCalledWith( - expect.objectContaining(set({}, 'body.doc.output.content', '12')) + expect.objectContaining(set({}, 'doc.output.content', '12')) ); expect(client.index).toHaveBeenCalledTimes(2); expect(client.index).toHaveBeenNthCalledWith( @@ -300,7 +297,7 @@ describe('ContentStream', () => { id: expect.any(String), index: '.kibana-reporting', op_type: 'create', - body: { + document: { '@timestamp': '1970-01-01T00:00:00.000Z', parent_id: 'something', output: { @@ -316,7 +313,7 @@ describe('ContentStream', () => { id: expect.any(String), index: '.kibana-reporting', op_type: 'create', - body: { + document: { '@timestamp': '1970-01-01T00:00:00.000Z', parent_id: 'something', output: { @@ -336,7 +333,7 @@ describe('ContentStream', () => { expect(client.update).toHaveBeenCalledTimes(1); expect(client.update).toHaveBeenCalledWith( expect.objectContaining( - set({}, 'body.doc.output.content', Buffer.from('123').toString('base64')) + set({}, 'doc.output.content', Buffer.from('123').toString('base64')) ) ); expect(client.index).toHaveBeenCalledTimes(2); @@ -346,7 +343,7 @@ describe('ContentStream', () => { id: expect.any(String), index: '.kibana-reporting', op_type: 'create', - body: { + document: { parent_id: 'something', '@timestamp': '1970-01-01T00:00:00.000Z', output: { @@ -362,7 +359,7 @@ describe('ContentStream', () => { id: expect.any(String), index: '.kibana-reporting', op_type: 'create', - body: { + document: { parent_id: 'something', '@timestamp': '1970-01-01T00:00:00.000Z', output: { @@ -384,8 +381,8 @@ describe('ContentStream', () => { const [[deleteRequest]] = client.deleteByQuery.mock.calls; const [[updateRequest]] = client.update.mock.calls; - expect(deleteRequest).toHaveProperty('body.query.match.parent_id', 'something'); - expect(updateRequest).toHaveProperty('body.doc.output.content', ''); + expect(deleteRequest).toHaveProperty('query.match.parent_id', 'something'); + expect(updateRequest).toHaveProperty('doc.output.content', ''); }); }); }); diff --git a/x-pack/platform/plugins/private/reporting/server/lib/content_stream.ts b/x-pack/platform/plugins/private/reporting/server/lib/content_stream.ts index e5006a4a45268..9fd313ffc1d59 100644 --- a/x-pack/platform/plugins/private/reporting/server/lib/content_stream.ts +++ b/x-pack/platform/plugins/private/reporting/server/lib/content_stream.ts @@ -111,7 +111,7 @@ export class ContentStream extends Duplex { this.logger.debug(`Reading report contents.`); - const response = await this.client.search({ body, index }); + const response = await this.client.search({ ...body, index }); const hits = response?.hits?.hits?.[0]; this.jobSize = hits?._source?.output?.size; @@ -139,7 +139,7 @@ export class ContentStream extends Duplex { this.logger.debug(`Reading chunk #${this.chunksRead}.`); const response = await this.client.search({ - body, + ...body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY, }); const hits = response?.hits?.hits?.[0]; @@ -179,10 +179,8 @@ export class ContentStream extends Duplex { await this.client.deleteByQuery({ index, - body: { - query: { - match: { parent_id: id }, - }, + query: { + match: { parent_id: id }, }, }); } @@ -192,10 +190,8 @@ export class ContentStream extends Duplex { const body = await this.client.update({ ...this.document, - body: { - doc: { - output: { content }, - }, + doc: { + output: { content }, }, }); @@ -212,7 +208,7 @@ export class ContentStream extends Duplex { id, index: REPORTING_DATA_STREAM_ALIAS, op_type: 'create', - body: { + document: { parent_id: parentId, '@timestamp': new Date(0).toISOString(), // required for data streams compatibility output: { diff --git a/x-pack/platform/plugins/private/reporting/server/lib/store/store.test.ts b/x-pack/platform/plugins/private/reporting/server/lib/store/store.test.ts index 3d5b5169d9c14..cece2608f4c48 100644 --- a/x-pack/platform/plugins/private/reporting/server/lib/store/store.test.ts +++ b/x-pack/platform/plugins/private/reporting/server/lib/store/store.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { JOB_STATUS } from '@kbn/reporting-common'; import { ReportDocument } from '@kbn/reporting-common/types'; diff --git a/x-pack/platform/plugins/private/reporting/server/lib/store/store.ts b/x-pack/platform/plugins/private/reporting/server/lib/store/store.ts index 85da045996279..671a9dbc924b1 100644 --- a/x-pack/platform/plugins/private/reporting/server/lib/store/store.ts +++ b/x-pack/platform/plugins/private/reporting/server/lib/store/store.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient, Logger } from '@kbn/core/server'; import { ILM_POLICY_NAME, JOB_STATUS } from '@kbn/reporting-common'; import type { @@ -141,7 +141,7 @@ export class ReportingStore { id: report._id, refresh: 'wait_for' as estypes.Refresh, op_type: 'create' as const, - body: { + document: { ...report.toReportSource(), ...sourceDoc({ process_expiration: new Date(0).toISOString(), diff --git a/x-pack/platform/plugins/private/reporting/server/lib/tasks/execute_report.test.ts b/x-pack/platform/plugins/private/reporting/server/lib/tasks/execute_report.test.ts index 1abac28bd3c41..b5920e59ab5fd 100644 --- a/x-pack/platform/plugins/private/reporting/server/lib/tasks/execute_report.test.ts +++ b/x-pack/platform/plugins/private/reporting/server/lib/tasks/execute_report.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { KibanaShuttingDownError } from '@kbn/reporting-common'; import { ReportDocument } from '@kbn/reporting-common/types'; diff --git a/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.test.ts b/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.test.ts index dd580773bc502..d9fdf01388729 100644 --- a/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.test.ts +++ b/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.test.ts @@ -44,31 +44,27 @@ describe('jobsQuery', () => { expect(client.search).toHaveBeenNthCalledWith( 1, expect.objectContaining({ - body: expect.objectContaining({ - size: 10, - from: 10, - query: set( - {}, - 'constant_score.filter.bool.must', - expect.arrayContaining([ - { term: { created_by: 'somebody' } }, - { ids: { values: ['id1', 'id2'] } }, - ]) - ), - }), + size: 10, + from: 10, + query: set( + {}, + 'constant_score.filter.bool.must', + expect.arrayContaining([ + { term: { created_by: 'somebody' } }, + { ids: { values: ['id1', 'id2'] } }, + ]) + ), }) ); expect(client.search).toHaveBeenNthCalledWith( 2, expect.objectContaining({ - body: expect.objectContaining({ - query: set( - {}, - 'constant_score.filter.bool.must', - expect.not.arrayContaining([{ ids: expect.any(Object) }]) - ), - }), + query: set( + {}, + 'constant_score.filter.bool.must', + expect.not.arrayContaining([{ ids: expect.any(Object) }]) + ), }) ); }); @@ -109,13 +105,11 @@ describe('jobsQuery', () => { expect(client.count).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: set( - {}, - 'constant_score.filter.bool.must', - expect.arrayContaining([{ term: { created_by: 'somebody' } }]) - ), - }), + query: set( + {}, + 'constant_score.filter.bool.must', + expect.arrayContaining([{ term: { created_by: 'somebody' } }]) + ), }) ); }); @@ -139,16 +133,11 @@ describe('jobsQuery', () => { expect(client.search).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: set( - {}, - 'constant_score.filter.bool.must', - expect.arrayContaining([ - { term: { _id: 'id1' } }, - { term: { created_by: 'somebody' } }, - ]) - ), - }), + query: set( + {}, + 'constant_score.filter.bool.must', + expect.arrayContaining([{ term: { _id: 'id1' } }, { term: { created_by: 'somebody' } }]) + ), }) ); }); @@ -192,13 +181,11 @@ describe('jobsQuery', () => { expect(client.search).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: set( - {}, - 'constant_score.filter.bool.must', - expect.arrayContaining([{ term: { _id: 'id1' } }]) - ), - }), + query: set( + {}, + 'constant_score.filter.bool.must', + expect.arrayContaining([{ term: { _id: 'id1' } }]) + ), }) ); }); diff --git a/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.ts b/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.ts index 453a5cfb40c6d..b7f1cc6b48661 100644 --- a/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.ts +++ b/x-pack/platform/plugins/private/reporting/server/routes/common/jobs/jobs_query.ts @@ -93,7 +93,7 @@ export function jobsQueryFactory( }); const response = (await execQuery((elasticsearchClient) => - elasticsearchClient.search({ body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY }) + elasticsearchClient.search({ ...body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY }) )) as estypes.SearchResponse; return ( @@ -124,7 +124,7 @@ export function jobsQueryFactory( }; const response = await execQuery((elasticsearchClient) => - elasticsearchClient.count({ body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY }) + elasticsearchClient.count({ ...body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY }) ); return response?.count ?? 0; @@ -154,7 +154,7 @@ export function jobsQueryFactory( const response = await execQuery((elasticsearchClient) => elasticsearchClient.search({ - body, + ...body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY, }) ); @@ -188,7 +188,7 @@ export function jobsQueryFactory( const response = await execQuery((elasticsearchClient) => elasticsearchClient.search({ - body, + ...body, index: REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY, }) ); diff --git a/x-pack/platform/plugins/private/reporting/server/routes/internal/deprecations/deprecations.ts b/x-pack/platform/plugins/private/reporting/server/routes/internal/deprecations/deprecations.ts index daf56d7233b40..f112473cd4207 100644 --- a/x-pack/platform/plugins/private/reporting/server/routes/internal/deprecations/deprecations.ts +++ b/x-pack/platform/plugins/private/reporting/server/routes/internal/deprecations/deprecations.ts @@ -26,15 +26,13 @@ const getAuthzWrapper = try { const body = await elasticsearch.client.asCurrentUser.security.hasPrivileges({ - body: { - index: [ - { - privileges: ['manage'], // required to do anything with the reporting indices - names: [REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY], - allow_restricted_indices: true, - }, - ], - }, + index: [ + { + privileges: ['manage'], // required to do anything with the reporting indices + names: [REPORTING_DATA_STREAM_WILDCARD_WITH_LEGACY], + allow_restricted_indices: true, + }, + ], }); if (!body.has_all_requested) { diff --git a/x-pack/platform/plugins/private/reporting/server/routes/internal/management/integration_tests/jobs.test.ts b/x-pack/platform/plugins/private/reporting/server/routes/internal/management/integration_tests/jobs.test.ts index ad65976d99f55..be33d24d03f6e 100644 --- a/x-pack/platform/plugins/private/reporting/server/routes/internal/management/integration_tests/jobs.test.ts +++ b/x-pack/platform/plugins/private/reporting/server/routes/internal/management/integration_tests/jobs.test.ts @@ -13,7 +13,7 @@ jest.mock('../../../../lib/content_stream', () => ({ getContentStream: jest.fn(), })); -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { setupServer } from '@kbn/core-test-helpers-test-utils'; import { ElasticsearchClientMock, coreMock } from '@kbn/core/server/mocks'; import { licensingMock } from '@kbn/licensing-plugin/server/mocks'; diff --git a/x-pack/platform/plugins/private/reporting/server/routes/public/integration_tests/jobs.test.ts b/x-pack/platform/plugins/private/reporting/server/routes/public/integration_tests/jobs.test.ts index 8afb1d2aa25b0..e754102d39490 100644 --- a/x-pack/platform/plugins/private/reporting/server/routes/public/integration_tests/jobs.test.ts +++ b/x-pack/platform/plugins/private/reporting/server/routes/public/integration_tests/jobs.test.ts @@ -13,7 +13,7 @@ import { BehaviorSubject } from 'rxjs'; import { Readable } from 'stream'; import supertest from 'supertest'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { setupServer } from '@kbn/core-test-helpers-test-utils'; import { coreMock, type ElasticsearchClientMock } from '@kbn/core/server/mocks'; import { licensingMock } from '@kbn/licensing-plugin/server/mocks'; diff --git a/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts b/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts index 595ee685efe6c..c4c9187307031 100644 --- a/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts +++ b/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts @@ -6,7 +6,7 @@ */ import { get } from 'lodash'; import { ElasticsearchClient } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DataViewType } from '@kbn/data-views-plugin/common'; // elasticsearch index.max_result_window default value @@ -36,13 +36,11 @@ export async function fetchRollupIndexPatterns(kibanaIndex: string, esClient: El index: kibanaIndex, ignore_unavailable: true, filter_path: ['hits.hits._id'], - body: { - query: { - bool: { - filter: { - term: { - 'index-pattern.type': DataViewType.ROLLUP, - }, + query: { + bool: { + filter: { + term: { + 'index-pattern.type': DataViewType.ROLLUP, }, }, }, @@ -71,13 +69,11 @@ const getSavedObjectsList = async ({ filter: ESFilterProps; }) => { const esResponse = await esClient.search({ - body: { - search_after: searchAfter, - sort: [{ updated_at: 'asc' }], - query: { - bool: { - filter, - }, + search_after: searchAfter, + sort: [{ updated_at: 'asc' }], + query: { + bool: { + filter, }, }, ignore_unavailable: true, diff --git a/x-pack/platform/plugins/private/rollup/server/routes/api/jobs/register_create_route.ts b/x-pack/platform/plugins/private/rollup/server/routes/api/jobs/register_create_route.ts index 7abb7e78f8c7a..ec92ab9b4204e 100644 --- a/x-pack/platform/plugins/private/rollup/server/routes/api/jobs/register_create_route.ts +++ b/x-pack/platform/plugins/private/rollup/server/routes/api/jobs/register_create_route.ts @@ -37,13 +37,10 @@ export const registerCreateRoute = ({ license.guardApiRoute(async (context, request, response) => { const { client: clusterClient } = (await context.core).elasticsearch; try { - const { id, ...rest } = request.body.job; + const { id } = request.body.job; // Create job. - await clusterClient.asCurrentUser.rollup.putJob({ - id, - // @ts-expect-error type mismatch on RollupPutJobRequest.body - body: rest, - }); + // @ts-expect-error elasticsearch@9.0.0 missing mandatory fields like cron, groups, index_pattern, page_size, rollup_index + await clusterClient.asCurrentUser.rollup.putJob(request.body.job); // Then request the newly created job. const results = await clusterClient.asCurrentUser.rollup.getJobs({ id }); return response.ok({ body: results.jobs[0] }); diff --git a/x-pack/platform/plugins/private/snapshot_restore/common/lib/snapshot_serialization.ts b/x-pack/platform/plugins/private/snapshot_restore/common/lib/snapshot_serialization.ts index 70cef8e16bc46..2cab6d5addbc6 100644 --- a/x-pack/platform/plugins/private/snapshot_restore/common/lib/snapshot_serialization.ts +++ b/x-pack/platform/plugins/private/snapshot_restore/common/lib/snapshot_serialization.ts @@ -8,6 +8,7 @@ import { sortBy } from 'lodash'; import { flow, map, flatten, uniq } from 'lodash/fp'; +import type { SlmRetention } from '@elastic/elasticsearch/lib/api/types'; import { SnapshotDetails, SnapshotDetailsEs, @@ -175,9 +176,7 @@ export function serializeSnapshotConfig(snapshotConfig: SnapshotConfig): Snapsho }, {}); } -export function deserializeSnapshotRetention( - snapshotRetentionEs: SnapshotRetentionEs -): SnapshotRetention { +export function deserializeSnapshotRetention(snapshotRetentionEs: SlmRetention): SnapshotRetention { const { expire_after: expireAfter, max_count: maxCount, @@ -213,7 +212,7 @@ export function deserializeSnapshotRetention( export function serializeSnapshotRetention( snapshotRetention: SnapshotRetention -): SnapshotRetentionEs | undefined { +): SlmRetention | undefined { const { expireAfterValue, expireAfterUnit, minCount, maxCount } = snapshotRetention; const snapshotRetentionEs: SnapshotRetentionEs = { diff --git a/x-pack/platform/plugins/private/snapshot_restore/common/lib/time_serialization.ts b/x-pack/platform/plugins/private/snapshot_restore/common/lib/time_serialization.ts index 7fc25b38d2461..a1fd996520287 100644 --- a/x-pack/platform/plugins/private/snapshot_restore/common/lib/time_serialization.ts +++ b/x-pack/platform/plugins/private/snapshot_restore/common/lib/time_serialization.ts @@ -5,11 +5,17 @@ * 2.0. */ +import type { Duration } from '@elastic/elasticsearch/lib/api/types'; import { TIME_UNITS } from '../constants'; -export const deserializeTime = (time: string) => { +export const deserializeTime = (time: Duration) => { const timeUnits = Object.values(TIME_UNITS); + if (typeof time !== 'string') { + // Apart from string, time can be -1 or 0. In those cases, we take them as invalid/empty times. + return {}; + } + const timeUnit = timeUnits.find((unit) => { const unitIndex = time.indexOf(unit); return unitIndex !== -1 && unitIndex === time.length - 1; diff --git a/x-pack/platform/plugins/private/snapshot_restore/common/types/policy.ts b/x-pack/platform/plugins/private/snapshot_restore/common/types/policy.ts index 67f7e01887ae0..5a7835099792a 100644 --- a/x-pack/platform/plugins/private/snapshot_restore/common/types/policy.ts +++ b/x-pack/platform/plugins/private/snapshot_restore/common/types/policy.ts @@ -5,12 +5,8 @@ * 2.0. */ -import { - SnapshotConfig, - SnapshotConfigEs, - SnapshotRetention, - SnapshotRetentionEs, -} from './snapshot'; +import type { SlmRetention } from '@elastic/elasticsearch/lib/api/types'; +import { SnapshotConfig, SnapshotConfigEs, SnapshotRetention } from './snapshot'; export interface SlmPolicyPayload { name: string; snapshotName: string; @@ -58,7 +54,7 @@ export interface SlmPolicyEs { schedule: string; repository: string; config?: SnapshotConfigEs; - retention?: SnapshotRetentionEs; + retention?: SlmRetention; }; next_execution: string; next_execution_millis: number; diff --git a/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/app.ts b/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/app.ts index b933e8c7ec67a..b044e45c59c83 100644 --- a/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/app.ts +++ b/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/app.ts @@ -60,9 +60,7 @@ export function registerAppRoutes({ // Get cluster privileges const { has_all_requested: hasAllPrivileges, cluster } = await clusterClient.asCurrentUser.security.hasPrivileges({ - body: { - cluster: [...APP_REQUIRED_CLUSTER_PRIVILEGES, ...APP_SLM_CLUSTER_PRIVILEGES], - }, + cluster: [...APP_REQUIRED_CLUSTER_PRIVILEGES, ...APP_SLM_CLUSTER_PRIVILEGES], }); // Find missing cluster privileges and set overall app privileges diff --git a/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/policy.ts b/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/policy.ts index 32cd1ca548da4..bd96cab5df9bb 100644 --- a/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/policy.ts +++ b/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/policy.ts @@ -296,11 +296,9 @@ export function registerPolicyRoutes({ try { const response = await clusterClient.asCurrentUser.cluster.putSettings({ - body: { - persistent: { - slm: { - retention_schedule: retentionSchedule, - }, + persistent: { + slm: { + retention_schedule: retentionSchedule, }, }, }); diff --git a/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/repositories.ts b/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/repositories.ts index f131ad34bb100..af060c2f67302 100644 --- a/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/repositories.ts +++ b/x-pack/platform/plugins/private/snapshot_restore/server/routes/api/repositories.ts @@ -308,7 +308,7 @@ export function registerRepositoriesRoutes({ try { const response = await clusterClient.asCurrentUser.snapshot.createRepository({ name, - body: { + repository: { // @ts-expect-error upgrade to @elastic/elasticsearch v8.13.0: can't be string, only valid "source" type, // TODO: Bring {@link RepositorySettings} in line with {@link SnapshotRepositorySettings} diff --git a/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_license.ts b/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_license.ts index 4a13dd72f8cef..551034a61a0ac 100644 --- a/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_license.ts +++ b/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_license.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient } from '@kbn/core/server'; export type ESLicense = estypes.LicenseGetLicenseInformation; diff --git a/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts b/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts index 436acb643d8a4..7a210e218b93a 100644 --- a/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts +++ b/x-pack/platform/plugins/private/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { coreMock, elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { getStatsWithXpack } from './get_stats_with_xpack'; import { SavedObjectsClient } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/private/transform/common/constants.ts b/x-pack/platform/plugins/private/transform/common/constants.ts index a1fe8d7289059..60ae86c9cf236 100644 --- a/x-pack/platform/plugins/private/transform/common/constants.ts +++ b/x-pack/platform/plugins/private/transform/common/constants.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import type { LicenseType } from '@kbn/licensing-plugin/common/types'; diff --git a/x-pack/platform/plugins/private/transform/common/types/pivot_aggs.ts b/x-pack/platform/plugins/private/transform/common/types/pivot_aggs.ts index ce9c0f9e0e1ed..abcddc1392cbe 100644 --- a/x-pack/platform/plugins/private/transform/common/types/pivot_aggs.ts +++ b/x-pack/platform/plugins/private/transform/common/types/pivot_aggs.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { AggName } from './aggregations'; export const PIVOT_SUPPORTED_AGGS = { diff --git a/x-pack/platform/plugins/private/transform/common/types/transform_stats.ts b/x-pack/platform/plugins/private/transform/common/types/transform_stats.ts index 5b846055dc941..324d2f0a0bd66 100644 --- a/x-pack/platform/plugins/private/transform/common/types/transform_stats.ts +++ b/x-pack/platform/plugins/private/transform/common/types/transform_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/plugins/private/transform/public/app/hooks/use_data_search.ts b/x-pack/platform/plugins/private/transform/public/app/hooks/use_data_search.ts index 7c5d45e5a56fd..4f0007daa4c42 100644 --- a/x-pack/platform/plugins/private/transform/public/app/hooks/use_data_search.ts +++ b/x-pack/platform/plugins/private/transform/public/app/hooks/use_data_search.ts @@ -8,7 +8,7 @@ import { useQuery } from '@tanstack/react-query'; import { lastValueFrom } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IKibanaSearchRequest } from '@kbn/search-types'; diff --git a/x-pack/platform/plugins/private/transform/public/app/hooks/use_index_data.ts b/x-pack/platform/plugins/private/transform/public/app/hooks/use_index_data.ts index 16e41eb05cb4f..c0f1f3b718ca4 100644 --- a/x-pack/platform/plugins/private/transform/public/app/hooks/use_index_data.ts +++ b/x-pack/platform/plugins/private/transform/public/app/hooks/use_index_data.ts @@ -7,7 +7,7 @@ import { useEffect, useMemo, useRef } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiDataGridColumn } from '@elastic/eui'; import { reportPerformanceMetricEvent } from '@kbn/ebt-tools'; @@ -152,17 +152,15 @@ export const useIndexData = (options: UseIndexDataOptions): UseIndexDataReturnTy } = useDataSearch( { index: indexPattern, - body: { - fields: ['*'], - _source: false, - query: isDefaultQuery(query) ? defaultQuery : queryWithBaseFilterCriteria, - from: pagination.pageIndex * pagination.pageSize, - size: pagination.pageSize, - ...(Object.keys(sort).length > 0 ? { sort } : {}), - ...(isRuntimeMappings(combinedRuntimeMappings) - ? { runtime_mappings: combinedRuntimeMappings } - : {}), - }, + fields: ['*'], + _source: false, + query: isDefaultQuery(query) ? defaultQuery : queryWithBaseFilterCriteria, + from: pagination.pageIndex * pagination.pageSize, + size: pagination.pageSize, + ...(Object.keys(sort).length > 0 ? { sort } : {}), + ...(isRuntimeMappings(combinedRuntimeMappings) + ? { runtime_mappings: combinedRuntimeMappings } + : {}), }, // Check whether fetching should be enabled dataViewFields.length > 0 diff --git a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx index 04793ee426cca..26f8e559d0995 100644 --- a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx +++ b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx @@ -16,7 +16,7 @@ import React, { } from 'react'; import useUpdateEffect from 'react-use/lib/useUpdateEffect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; import { EuiComboBox, EuiFormRow } from '@elastic/eui'; @@ -77,25 +77,23 @@ export const FilterTermForm: FilterAggConfigTerm['aggTypeConfig']['FilterAggForm const { data, isError, isLoading } = useDataSearch( { index: dataView!.title, - body: { - ...(runtimeMappings !== undefined ? { runtime_mappings: runtimeMappings } : {}), - query: { - wildcard: { - [selectedField!]: { - value: `*${searchValue}*`, - }, + ...(runtimeMappings !== undefined ? { runtime_mappings: runtimeMappings } : {}), + query: { + wildcard: { + [selectedField!]: { + value: `*${searchValue}*`, }, }, - aggs: { - field_values: { - terms: { - field: selectedField, - size: 10, - }, + }, + aggs: { + field_values: { + terms: { + field: selectedField, + size: 10, }, }, - size: 0, }, + size: 0, }, // Check whether fetching should be enabled selectedField !== undefined diff --git a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/config.ts b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/config.ts index 96e6f0dbb3a3a..c608c08b6a6aa 100644 --- a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/config.ts +++ b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/config.ts @@ -7,7 +7,7 @@ import { isPopulatedObject } from '@kbn/ml-is-populated-object'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { PivotAggsConfigBase, PivotAggsConfigWithUiBase, diff --git a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/types.ts b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/types.ts index 3c7c92dc5e5fb..2805a36c7537e 100644 --- a/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/types.ts +++ b/x-pack/platform/plugins/private/transform/public/app/sections/create_transform/components/step_define/common/top_metrics_agg/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { PivotAggsConfigWithExtra, SortDirection, diff --git a/x-pack/platform/plugins/private/transform/server/lib/alerting/transform_health_rule_type/transform_health_service.ts b/x-pack/platform/plugins/private/transform/server/lib/alerting/transform_health_rule_type/transform_health_service.ts index 55b70099d67ea..130e1a724d98e 100644 --- a/x-pack/platform/plugins/private/transform/server/lib/alerting/transform_health_rule_type/transform_health_service.ts +++ b/x-pack/platform/plugins/private/transform/server/lib/alerting/transform_health_rule_type/transform_health_service.ts @@ -7,7 +7,7 @@ import type { ElasticsearchClient } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { keyBy, memoize, partition } from 'lodash'; import type { RulesClient } from '@kbn/alerting-plugin/server'; import type { FieldFormatsRegistry } from '@kbn/field-formats-plugin/common'; diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/audit_messages/route_handler.ts b/x-pack/platform/plugins/private/transform/server/routes/api/audit_messages/route_handler.ts index aeea12c881a46..0d04a152523e8 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/audit_messages/route_handler.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/audit_messages/route_handler.ts @@ -78,13 +78,11 @@ export const routeHandler: RequestHandler< index: TRANSFORM_NOTIFICATIONS_INDEX, ignore_unavailable: true, size: DEFAULT_MAX_AUDIT_MESSAGE_SIZE, - body: { - sort: [ - { [sortField]: { order: sortDirection } }, - { transform_id: { order: 'asc' as const } }, - ], - query, - }, + sort: [ + { [sortField]: { order: sortDirection } }, + { transform_id: { order: 'asc' as const } }, + ], + query, track_total_hits: true, }); const totalHits = diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/register_route.ts b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/register_route.ts index 9bd95b02d60ae..566563fd124d9 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/register_route.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/register_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { addInternalBasePath } from '../../../../common/constants'; diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/route_handler.ts b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/route_handler.ts index 4bf9a03b64882..386e14b7d684e 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/route_handler.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_all/route_handler.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RequestHandler } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_nodes/route_handler_factory.ts b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_nodes/route_handler_factory.ts index 10171f948c2ad..95ef4b1051314 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_nodes/route_handler_factory.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_nodes/route_handler_factory.ts @@ -41,9 +41,7 @@ export const routeHandlerFactory: ( if (license.getStatus().isSecurityEnabled === true) { const { has_all_requested: hasAllPrivileges } = await esClient.asCurrentUser.security.hasPrivileges({ - body: { - cluster: NODES_INFO_PRIVILEGES, - }, + cluster: NODES_INFO_PRIVILEGES, }); if (!hasAllPrivileges) { diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_preview/route_handler.ts b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_preview/route_handler.ts index b6beb641f0b55..ff98abfc170ab 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_preview/route_handler.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_preview/route_handler.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RequestHandler } from '@kbn/core/server'; @@ -23,12 +23,9 @@ export const routeHandler: RequestHandler< try { const reqBody = req.body; const esClient = (await ctx.core).elasticsearch.client; - const body = await esClient.asCurrentUser.transform.previewTransform( - { - body: reqBody, - }, - { maxRetries: 0 } - ); + const body = await esClient.asCurrentUser.transform.previewTransform(reqBody, { + maxRetries: 0, + }); if (isLatestTransform(reqBody)) { // for the latest transform mappings properties have to be retrieved from the source const fieldCapsResponse = await esClient.asCurrentUser.fieldCaps( diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/register_route.ts b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/register_route.ts index 40f21ed1f84b5..a224f57b20a8f 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/register_route.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/register_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { getTransformStatsQuerySchema, diff --git a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/route_handler.ts b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/route_handler.ts index 5f44b2b732d21..d54d5278984a3 100644 --- a/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/route_handler.ts +++ b/x-pack/platform/plugins/private/transform/server/routes/api/transforms_stats_all/route_handler.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RequestHandler } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/common/types.ts b/x-pack/platform/plugins/private/upgrade_assistant/common/types.ts index 7d614463f4977..bfcf54baec771 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/common/types.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/common/types.ts @@ -6,7 +6,7 @@ */ import { HealthReportImpact } from '@elastic/elasticsearch/lib/api/types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObject } from '@kbn/core/types'; import type { DataStreamsAction } from './data_stream_types'; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/__fixtures__/health_indicators.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/__fixtures__/health_indicators.ts index e62f8cbb43852..b56e60dc56f1f 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/__fixtures__/health_indicators.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/__fixtures__/health_indicators.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; export const diskIndicatorGreen: estypes.HealthReportDiskIndicator = { status: 'green', diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/data_streams/data_stream_reindex_service.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/data_streams/data_stream_reindex_service.ts index eb3c3f3551f78..5411f1e326e2a 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/data_streams/data_stream_reindex_service.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/data_streams/data_stream_reindex_service.ts @@ -93,16 +93,14 @@ export const dataStreamReindexServiceFactory = ({ const names = [dataStreamName]; const resp = await esClient.security.hasPrivileges({ - body: { - cluster: ['manage', 'cancel_task'], - index: [ - { - names, - allow_restricted_indices: true, - privileges: ['all'], - }, - ], - }, + cluster: ['manage', 'cancel_task'], + index: [ + { + names, + allow_restricted_indices: true, + privileges: ['all'], + }, + ], }); return resp.has_all_requested; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts index 2a448e78e370a..8473f5b0503c3 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts @@ -29,15 +29,13 @@ describe('setDeprecationLogging', () => { const dataClient = elasticsearchServiceMock.createScopedClusterClient(); await setDeprecationLogging(dataClient, true); expect(dataClient.asCurrentUser.cluster.putSettings).toHaveBeenCalledWith({ - body: { - persistent: { - 'logger.deprecation': 'WARN', - 'cluster.deprecation_indexing.enabled': true, - }, - transient: { - 'logger.deprecation': 'WARN', - 'cluster.deprecation_indexing.enabled': true, - }, + persistent: { + 'logger.deprecation': 'WARN', + 'cluster.deprecation_indexing.enabled': true, + }, + transient: { + 'logger.deprecation': 'WARN', + 'cluster.deprecation_indexing.enabled': true, }, }); }); @@ -48,15 +46,13 @@ describe('setDeprecationLogging', () => { const dataClient = elasticsearchServiceMock.createScopedClusterClient(); await setDeprecationLogging(dataClient, false); expect(dataClient.asCurrentUser.cluster.putSettings).toHaveBeenCalledWith({ - body: { - persistent: { - 'logger.deprecation': 'ERROR', - 'cluster.deprecation_indexing.enabled': false, - }, - transient: { - 'logger.deprecation': 'ERROR', - 'cluster.deprecation_indexing.enabled': false, - }, + persistent: { + 'logger.deprecation': 'ERROR', + 'cluster.deprecation_indexing.enabled': false, + }, + transient: { + 'logger.deprecation': 'ERROR', + 'cluster.deprecation_indexing.enabled': false, }, }); }); diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.ts index 081903ff0f0ee..300dc21ffd13d 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecation_logging_apis.ts @@ -27,20 +27,18 @@ export async function setDeprecationLogging( isEnabled: boolean ): Promise { const response = await dataClient.asCurrentUser.cluster.putSettings({ - body: { - persistent: { - 'logger.deprecation': isEnabled ? 'WARN' : 'ERROR', - 'cluster.deprecation_indexing.enabled': isEnabled, - }, - /* - * If we only set the persistent setting, we can end up in a situation in which a user has - * set transient on/off. And when toggling and reloading the page the transient setting will - * have priority over it thus "overriding" whatever the user selected. - */ - transient: { - 'logger.deprecation': isEnabled ? 'WARN' : 'ERROR', - 'cluster.deprecation_indexing.enabled': isEnabled, - }, + persistent: { + 'logger.deprecation': isEnabled ? 'WARN' : 'ERROR', + 'cluster.deprecation_indexing.enabled': isEnabled, + }, + /* + * If we only set the persistent setting, we can end up in a situation in which a user has + * set transient on/off. And when toggling and reloading the page the transient setting will + * have priority over it thus "overriding" whatever the user selected. + */ + transient: { + 'logger.deprecation': isEnabled ? 'WARN' : 'ERROR', + 'cluster.deprecation_indexing.enabled': isEnabled, }, }); diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/health_indicators.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/health_indicators.ts index 915ccc3ecbb42..41a54ab186e56 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/health_indicators.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/health_indicators.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { IScopedClusterClient } from '@kbn/core/server'; import { EnrichedDeprecationInfo } from '../../../common/types'; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/index.test.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/index.test.ts index 435c0257df927..f3b9a27c68d1d 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/index.test.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/index.test.ts @@ -7,7 +7,7 @@ import _ from 'lodash'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import fakeDeprecations from '../__fixtures__/fake_deprecations.json'; import * as healthIndicatorsMock from '../__fixtures__/health_indicators'; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts index 7726dceffb7d5..3ec5e8adab61c 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts @@ -101,20 +101,18 @@ describe('reindexService', () => { const hasRequired = await service.hasRequiredPrivileges('anIndex'); expect(hasRequired).toBe(true); expect(clusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - cluster: ['manage'], - index: [ - { - names: ['anIndex', `reindexed-v${currentMajor}-anIndex`], - allow_restricted_indices: true, - privileges: ['all'], - }, - { - names: ['.tasks'], - privileges: ['read'], - }, - ], - }, + cluster: ['manage'], + index: [ + { + names: ['anIndex', `reindexed-v${currentMajor}-anIndex`], + allow_restricted_indices: true, + privileges: ['all'], + }, + { + names: ['.tasks'], + privileges: ['read'], + }, + ], }); }); @@ -127,24 +125,22 @@ describe('reindexService', () => { const hasRequired = await service.hasRequiredPrivileges(`reindexed-v${prevMajor}-anIndex`); expect(hasRequired).toBe(true); expect(clusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - cluster: ['manage'], - index: [ - { - names: [ - `reindexed-v${prevMajor}-anIndex`, - `reindexed-v${currentMajor}-anIndex`, - 'anIndex', - ], - allow_restricted_indices: true, - privileges: ['all'], - }, - { - names: ['.tasks'], - privileges: ['read'], - }, - ], - }, + cluster: ['manage'], + index: [ + { + names: [ + `reindexed-v${prevMajor}-anIndex`, + `reindexed-v${currentMajor}-anIndex`, + 'anIndex', + ], + allow_restricted_indices: true, + privileges: ['all'], + }, + { + names: ['.tasks'], + privileges: ['read'], + }, + ], }); }); }); diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.ts index 31bfe99f34c75..3c06ee56edd75 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/reindex_service.ts @@ -163,7 +163,7 @@ export const reindexServiceFactory = ( const { indexName } = reindexOp.attributes; const putReadonly = await esClient.indices.putSettings({ index: indexName, - body: { blocks: { write: true } }, + settings: { blocks: { write: true } }, }); if (!putReadonly.acknowledged) { @@ -449,20 +449,18 @@ export const reindexServiceFactory = ( } const resp = await esClient.security.hasPrivileges({ - body: { - cluster: ['manage'], - index: [ - { - names, - allow_restricted_indices: true, - privileges: ['all'], - }, - { - names: ['.tasks'], - privileges: ['read'], - }, - ], - }, + cluster: ['manage'], + index: [ + { + names, + allow_restricted_indices: true, + privileges: ['all'], + }, + { + names: ['.tasks'], + privileges: ['read'], + }, + ], }); return resp.has_all_requested; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/types.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/types.ts index d046fa5f22f92..d8446cea224cf 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/types.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/lib/reindexing/types.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; interface Mapping { type?: string; diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/app.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/app.ts index e6e5bffcf2629..12063ba382d6f 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/app.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/app.ts @@ -73,15 +73,13 @@ export function registerAppRoutes({ index, cluster, } = await client.asCurrentUser.security.hasPrivileges({ - body: { - cluster: APP_LOGS_COUNT_CLUSTER_PRIVILEGES, - index: [ - { - names: [DEPRECATION_LOGS_INDEX], - privileges: APP_LOGS_COUNT_INDEX_PRIVILEGES, - }, - ], - }, + cluster: APP_LOGS_COUNT_CLUSTER_PRIVILEGES, + index: [ + { + names: [DEPRECATION_LOGS_INDEX], + privileges: APP_LOGS_COUNT_INDEX_PRIVILEGES, + }, + ], }); if (!hasAllPrivileges) { diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/cluster_settings.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/cluster_settings.ts index c264df3eceaf5..29124b778e713 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/cluster_settings.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/cluster_settings.ts @@ -65,7 +65,7 @@ export function registerClusterSettingsRoute({ ); const settingsResponse = await client.asCurrentUser.cluster.putSettings({ - body: settingsToDelete, + ...settingsToDelete, flat_settings: true, }); diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/deprecation_logging.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/deprecation_logging.ts index 65771c0b85815..2a8841f041ab1 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/deprecation_logging.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/deprecation_logging.ts @@ -111,21 +111,19 @@ export function registerDeprecationLoggingRoutes({ const body = await client.asCurrentUser.count({ index: DEPRECATION_LOGS_INDEX, - body: { - query: { - bool: { - must: { - range: { - '@timestamp': { - gte: request.query.from, - lte: now, - }, + query: { + bool: { + must: { + range: { + '@timestamp': { + gte: request.query.from, + lte: now, }, }, - must_not: { - terms: { - [DEPRECATION_LOGS_ORIGIN_FIELD]: [...APPS_WITH_DEPRECATION_LOGS], - }, + }, + must_not: { + terms: { + [DEPRECATION_LOGS_ORIGIN_FIELD]: [...APPS_WITH_DEPRECATION_LOGS], }, }, }, diff --git a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/update_index_settings.ts b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/update_index_settings.ts index f037381a9f52a..e05cf12c7cc69 100644 --- a/x-pack/platform/plugins/private/upgrade_assistant/server/routes/update_index_settings.ts +++ b/x-pack/platform/plugins/private/upgrade_assistant/server/routes/update_index_settings.ts @@ -44,7 +44,7 @@ export function registerUpdateSettingsRoute({ router }: RouteDependencies) { const settingsResponse = await client.asCurrentUser.indices.putSettings({ index: indexName, - body: settingsToDelete, + settings: settingsToDelete, }); return response.ok({ diff --git a/x-pack/platform/plugins/private/watcher/common/types/status_types.ts b/x-pack/platform/plugins/private/watcher/common/types/status_types.ts index b5dc2542820da..7f78f8314784c 100644 --- a/x-pack/platform/plugins/private/watcher/common/types/status_types.ts +++ b/x-pack/platform/plugins/private/watcher/common/types/status_types.ts @@ -6,7 +6,7 @@ */ import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../constants'; diff --git a/x-pack/platform/plugins/private/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts b/x-pack/platform/plugins/private/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts index ce0883940d0b2..a5064850c618e 100644 --- a/x-pack/platform/plugins/private/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts +++ b/x-pack/platform/plugins/private/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { IScopedClusterClient } from '@kbn/core/server'; import { get } from 'lodash'; import { ES_SCROLL_SETTINGS } from '../../../common/constants'; diff --git a/x-pack/platform/plugins/private/watcher/server/routes/api/indices/register_get_route.ts b/x-pack/platform/plugins/private/watcher/server/routes/api/indices/register_get_route.ts index 5736af1eb4228..1b371b0537113 100644 --- a/x-pack/platform/plugins/private/watcher/server/routes/api/indices/register_get_route.ts +++ b/x-pack/platform/plugins/private/watcher/server/routes/api/indices/register_get_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from '@kbn/core/server'; import { reduce, size } from 'lodash'; @@ -50,14 +50,12 @@ async function getIndices(dataClient: IScopedClusterClient, pattern: string, lim const response = await dataClient.asCurrentUser.search( { index: pattern, - body: { - size: 0, // no hits - aggs: { - indices: { - terms: { - field: '_index', - size: limit, - }, + size: 0, // no hits + aggs: { + indices: { + terms: { + field: '_index', + size: limit, }, }, }, diff --git a/x-pack/platform/plugins/private/watcher/server/routes/api/register_load_history_route.ts b/x-pack/platform/plugins/private/watcher/server/routes/api/register_load_history_route.ts index 8dd7bd722a654..b29763c905d0a 100644 --- a/x-pack/platform/plugins/private/watcher/server/routes/api/register_load_history_route.ts +++ b/x-pack/platform/plugins/private/watcher/server/routes/api/register_load_history_route.ts @@ -20,11 +20,9 @@ const paramsSchema = schema.object({ function fetchHistoryItem(dataClient: IScopedClusterClient, watchHistoryItemId: string) { return dataClient.asCurrentUser.search({ index: INDEX_NAMES.WATCHER_HISTORY, - body: { - query: { - bool: { - must: [{ term: { _id: watchHistoryItemId } }], - }, + query: { + bool: { + must: [{ term: { _id: watchHistoryItemId } }], }, }, }); diff --git a/x-pack/platform/plugins/private/watcher/server/routes/api/watches/register_delete_route.ts b/x-pack/platform/plugins/private/watcher/server/routes/api/watches/register_delete_route.ts index b34a1cd75fa35..97080195ad88d 100644 --- a/x-pack/platform/plugins/private/watcher/server/routes/api/watches/register_delete_route.ts +++ b/x-pack/platform/plugins/private/watcher/server/routes/api/watches/register_delete_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from '@kbn/core/server'; import { RouteDependencies } from '../../../types'; diff --git a/x-pack/platform/plugins/shared/actions/common/execution_log_types.ts b/x-pack/platform/plugins/shared/actions/common/execution_log_types.ts index 7784627b99c48..7f5e758ace3e1 100644 --- a/x-pack/platform/plugins/shared/actions/common/execution_log_types.ts +++ b/x-pack/platform/plugins/shared/actions/common/execution_log_types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; export interface IExecutionLog { id: string; diff --git a/x-pack/platform/plugins/shared/actions/server/actions_client/actions_client.test.ts b/x-pack/platform/plugins/shared/actions/server/actions_client/actions_client.test.ts index 14b8181278551..a2d7fb2014e95 100644 --- a/x-pack/platform/plugins/shared/actions/server/actions_client/actions_client.test.ts +++ b/x-pack/platform/plugins/shared/actions/server/actions_client/actions_client.test.ts @@ -50,7 +50,7 @@ import { getOAuthClientCredentialsAccessToken } from '../lib/get_oauth_client_cr import { OAuthParams } from '../routes/get_oauth_access_token'; import { eventLogClientMock } from '@kbn/event-log-plugin/server/event_log_client.mock'; import { GetGlobalExecutionKPIParams, GetGlobalExecutionLogParams } from '../../common'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DEFAULT_USAGE_API_URL } from '../config'; jest.mock('@kbn/core-saved-objects-utils-server', () => { diff --git a/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.test.ts b/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.test.ts index b2a13bc988cd1..2a054ab5f2761 100644 --- a/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.test.ts +++ b/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.test.ts @@ -842,31 +842,29 @@ describe('getAllUnsecured()', () => { expect(scopedClusterClient.asInternalUser.search).toHaveBeenCalledWith({ index: kibanaIndices, ignore_unavailable: true, - body: { - aggs: { - '1': { - filter: { - bool: { - must: { - nested: { - path: 'references', - query: { - bool: { - filter: { - bool: { - must: [ - { - term: { - 'references.id': '1', - }, + aggs: { + '1': { + filter: { + bool: { + must: { + nested: { + path: 'references', + query: { + bool: { + filter: { + bool: { + must: [ + { + term: { + 'references.id': '1', }, - { - term: { - 'references.type': 'action', - }, + }, + { + term: { + 'references.type': 'action', }, - ], - }, + }, + ], }, }, }, @@ -875,29 +873,29 @@ describe('getAllUnsecured()', () => { }, }, }, - testPreconfigured: { - filter: { - bool: { - must: { - nested: { - path: 'references', - query: { - bool: { - filter: { - bool: { - must: [ - { - term: { - 'references.id': 'testPreconfigured', - }, + }, + testPreconfigured: { + filter: { + bool: { + must: { + nested: { + path: 'references', + query: { + bool: { + filter: { + bool: { + must: [ + { + term: { + 'references.id': 'testPreconfigured', }, - { - term: { - 'references.type': 'action', - }, + }, + { + term: { + 'references.type': 'action', }, - ], - }, + }, + ], }, }, }, @@ -907,10 +905,10 @@ describe('getAllUnsecured()', () => { }, }, }, - size: 0, - query: { - match_all: {}, - }, + }, + size: 0, + query: { + match_all: {}, }, }); @@ -1020,31 +1018,29 @@ describe('getAllUnsecured()', () => { expect(scopedClusterClient.asInternalUser.search).toHaveBeenCalledWith({ index: kibanaIndices, ignore_unavailable: true, - body: { - aggs: { - '1': { - filter: { - bool: { - must: { - nested: { - path: 'references', - query: { - bool: { - filter: { - bool: { - must: [ - { - term: { - 'references.id': '1', - }, + aggs: { + '1': { + filter: { + bool: { + must: { + nested: { + path: 'references', + query: { + bool: { + filter: { + bool: { + must: [ + { + term: { + 'references.id': '1', }, - { - term: { - 'references.type': 'action', - }, + }, + { + term: { + 'references.type': 'action', }, - ], - }, + }, + ], }, }, }, @@ -1053,29 +1049,29 @@ describe('getAllUnsecured()', () => { }, }, }, - testPreconfigured: { - filter: { - bool: { - must: { - nested: { - path: 'references', - query: { - bool: { - filter: { - bool: { - must: [ - { - term: { - 'references.id': 'testPreconfigured', - }, + }, + testPreconfigured: { + filter: { + bool: { + must: { + nested: { + path: 'references', + query: { + bool: { + filter: { + bool: { + must: [ + { + term: { + 'references.id': 'testPreconfigured', }, - { - term: { - 'references.type': 'action', - }, + }, + { + term: { + 'references.type': 'action', }, - ], - }, + }, + ], }, }, }, @@ -1085,10 +1081,10 @@ describe('getAllUnsecured()', () => { }, }, }, - size: 0, - query: { - match_all: {}, - }, + }, + size: 0, + query: { + match_all: {}, }, }); diff --git a/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.ts b/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.ts index 70da68e1bd9d4..0242a6fe2aa04 100644 --- a/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.ts +++ b/x-pack/platform/plugins/shared/actions/server/application/connector/methods/get_all/get_all.ts @@ -8,7 +8,7 @@ /** * Get all actions with in-memory connectors */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { AuditLogger } from '@kbn/security-plugin-types-server'; import { ElasticsearchClient, Logger } from '@kbn/core/server'; import { omit } from 'lodash'; diff --git a/x-pack/platform/plugins/shared/actions/server/data/connector/search_connectors_so.ts b/x-pack/platform/plugins/shared/actions/server/data/connector/search_connectors_so.ts index ab549899348ae..78804623ed0de 100644 --- a/x-pack/platform/plugins/shared/actions/server/data/connector/search_connectors_so.ts +++ b/x-pack/platform/plugins/shared/actions/server/data/connector/search_connectors_so.ts @@ -15,12 +15,10 @@ export const searchConnectorsSo = async ({ return esClient.search({ index: kibanaIndices, ignore_unavailable: true, - body: { - aggs, - size: 0, - query: { - match_all: {}, - }, + aggs, + size: 0, + query: { + match_all: {}, }, }); }; diff --git a/x-pack/platform/plugins/shared/actions/server/data/connector/types/params.ts b/x-pack/platform/plugins/shared/actions/server/data/connector/types/params.ts index c23447fb37486..1786588fb54ee 100644 --- a/x-pack/platform/plugins/shared/actions/server/data/connector/types/params.ts +++ b/x-pack/platform/plugins/shared/actions/server/data/connector/types/params.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { SavedObjectsClient } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.test.ts b/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.test.ts index 0d889e53ca8c2..69c1b4a0ad9c1 100644 --- a/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.test.ts +++ b/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression } from '@kbn/es-query'; import { getExecutionLogAggregation, diff --git a/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.ts b/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.ts index ff11f831662cc..d800a3197e164 100644 --- a/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.ts @@ -6,7 +6,7 @@ */ import { KueryNode } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import Boom from '@hapi/boom'; import { flatMap, get, isEmpty } from 'lodash'; import { AggregateEventsBySavedObjectResult } from '@kbn/event-log-plugin/server'; diff --git a/x-pack/platform/plugins/shared/actions/server/monitoring/register_cluster_collector.ts b/x-pack/platform/plugins/shared/actions/server/monitoring/register_cluster_collector.ts index 23c4953b40d6e..b1ed0ecdf2ea8 100644 --- a/x-pack/platform/plugins/shared/actions/server/monitoring/register_cluster_collector.ts +++ b/x-pack/platform/plugins/shared/actions/server/monitoring/register_cluster_collector.ts @@ -7,7 +7,7 @@ import type { AggregationsKeyedPercentiles, AggregationsPercentilesAggregateBase, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { MonitoringCollectionSetup } from '@kbn/monitoring-collection-plugin/server'; import { aggregateTaskOverduePercentilesForType } from '@kbn/task-manager-plugin/server'; import { CoreSetup } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/shared/actions/server/usage/actions_telemetry.ts b/x-pack/platform/plugins/shared/actions/server/usage/actions_telemetry.ts index d0964266ea36c..c0423f6736420 100644 --- a/x-pack/platform/plugins/shared/actions/server/usage/actions_telemetry.ts +++ b/x-pack/platform/plugins/shared/actions/server/usage/actions_telemetry.ts @@ -7,7 +7,7 @@ import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, Logger } from '@kbn/core/server'; -import { AggregationsTermsAggregateBase } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsTermsAggregateBase } from '@elastic/elasticsearch/lib/api/types'; import { AvgActionRunOutcomeByConnectorTypeBucket, parseActionRunOutcomeByConnectorTypesBucket, @@ -71,17 +71,15 @@ export async function getTotalCount( }, }, }, - body: { - query: { - bool: { - filter: [{ term: { type: 'action' } }], - }, + query: { + bool: { + filter: [{ term: { type: 'action' } }], }, - aggs: { - byActionTypeId: { - terms: { - field: 'calcActionTypeId', - }, + }, + aggs: { + byActionTypeId: { + terms: { + field: 'calcActionTypeId', }, }, }, @@ -225,57 +223,55 @@ export async function getInUseTotalCount( >({ index: kibanaIndex, size: 0, - body: { - query: { - bool: { - filter: { - bool: { - must_not: { - term: { - type: 'action_task_params', - }, + query: { + bool: { + filter: { + bool: { + must_not: { + term: { + type: 'action_task_params', }, - must: mustQuery, }, + must: mustQuery, }, }, }, - aggs: { - refs: { - nested: { - path: 'references', - }, - aggs: { - actionRefIds: { - multi_terms: { - terms: [ - { - field: 'references.id', - }, - { - field: 'references.name', - }, - ], - }, + }, + aggs: { + refs: { + nested: { + path: 'references', + }, + aggs: { + actionRefIds: { + multi_terms: { + terms: [ + { + field: 'references.id', + }, + { + field: 'references.name', + }, + ], }, }, }, - actions: { - nested: { - path: 'alert.actions', - }, - aggs: { - actionRefIds: { - multi_terms: { - terms: [ - { - field: 'alert.actions.actionRef', - }, - { - field: 'alert.actions.actionTypeId', - }, - ], - }, + }, + actions: { + nested: { + path: 'alert.actions', + }, + aggs: { + actionRefIds: { + multi_terms: { + terms: [ + { + field: 'alert.actions.actionRef', + }, + { + field: 'alert.actions.actionTypeId', + }, + ], }, }, }, @@ -298,20 +294,18 @@ export async function getInUseTotalCount( }>({ index: kibanaIndex, _source_includes: ['action', 'namespaces'], - body: { - query: { - bool: { - must: [ - { - term: { type: 'action' }, - }, - { - terms: { - _id: Object.entries(aggs?.connectorIds ?? {}).map(([key]) => `action:${key}`), - }, + query: { + bool: { + must: [ + { + term: { type: 'action' }, + }, + { + terms: { + _id: Object.entries(aggs?.connectorIds ?? {}).map(([key]) => `action:${key}`), }, - ], - }, + }, + ], }, }, }); @@ -456,73 +450,71 @@ export async function getExecutionsPerDayCount( const actionResults = await esClient.search({ index: eventLogIndex, size: 0, - body: { - query: { - bool: { - filter: { - bool: { - must: [ - { - term: { 'event.action': 'execute' }, - }, - { - term: { 'event.provider': 'actions' }, - }, - { - range: { - '@timestamp': { - gte: 'now-1d', - }, + query: { + bool: { + filter: { + bool: { + must: [ + { + term: { 'event.action': 'execute' }, + }, + { + term: { 'event.provider': 'actions' }, + }, + { + range: { + '@timestamp': { + gte: 'now-1d', }, }, - ], - }, + }, + ], }, }, }, - aggs: { - totalExecutions: { - nested: { - path: 'kibana.saved_objects', - }, - aggs: { - refs: { - filter: { term: { 'kibana.saved_objects.type': 'action' } }, - aggs: { - byConnectorTypeId: { - terms: { - field: 'kibana.saved_objects.type_id', - }, + }, + aggs: { + totalExecutions: { + nested: { + path: 'kibana.saved_objects', + }, + aggs: { + refs: { + filter: { term: { 'kibana.saved_objects.type': 'action' } }, + aggs: { + byConnectorTypeId: { + terms: { + field: 'kibana.saved_objects.type_id', }, }, }, }, }, - failedExecutions: { - filter: { - bool: { - filter: [ - { - term: { - 'event.outcome': 'failure', - }, + }, + failedExecutions: { + filter: { + bool: { + filter: [ + { + term: { + 'event.outcome': 'failure', }, - ], - }, - }, - aggs: { - actionSavedObjects: { - nested: { - path: 'kibana.saved_objects', }, - aggs: { - refs: { - filter: { term: { 'kibana.saved_objects.type': 'action' } }, - aggs: { - byConnectorTypeId: { - terms: { - field: 'kibana.saved_objects.type_id', - }, + ], + }, + }, + aggs: { + actionSavedObjects: { + nested: { + path: 'kibana.saved_objects', + }, + aggs: { + refs: { + filter: { term: { 'kibana.saved_objects.type': 'action' } }, + aggs: { + byConnectorTypeId: { + terms: { + field: 'kibana.saved_objects.type_id', }, }, }, @@ -530,25 +522,25 @@ export async function getExecutionsPerDayCount( }, }, }, - avgDuration: { avg: { field: 'event.duration' } }, - avgDurationByType: { - nested: { - path: 'kibana.saved_objects', - }, - aggs: { - actionSavedObjects: { - filter: { term: { 'kibana.saved_objects.type': 'action' } }, - aggs: { - byTypeId: { - terms: { - field: 'kibana.saved_objects.type_id', - }, - aggs: { - refs: { - reverse_nested: {}, - aggs: { - avgDuration: { avg: { field: 'event.duration' } }, - }, + }, + avgDuration: { avg: { field: 'event.duration' } }, + avgDurationByType: { + nested: { + path: 'kibana.saved_objects', + }, + aggs: { + actionSavedObjects: { + filter: { term: { 'kibana.saved_objects.type': 'action' } }, + aggs: { + byTypeId: { + terms: { + field: 'kibana.saved_objects.type_id', + }, + aggs: { + refs: { + reverse_nested: {}, + aggs: { + avgDuration: { avg: { field: 'event.duration' } }, }, }, }, @@ -556,26 +548,26 @@ export async function getExecutionsPerDayCount( }, }, }, - count_connector_types_by_action_run_outcome_per_day: { - nested: { - path: 'kibana.saved_objects', - }, - aggs: { - actionSavedObjects: { - filter: { term: { 'kibana.saved_objects.type': 'action' } }, - aggs: { - connector_types: { - terms: { - field: 'kibana.saved_objects.type_id', - }, - aggs: { - outcome: { - reverse_nested: {}, - aggs: { - count: { - terms: { - field: 'event.outcome', - }, + }, + count_connector_types_by_action_run_outcome_per_day: { + nested: { + path: 'kibana.saved_objects', + }, + aggs: { + actionSavedObjects: { + filter: { term: { 'kibana.saved_objects.type': 'action' } }, + aggs: { + connector_types: { + terms: { + field: 'kibana.saved_objects.type_id', + }, + aggs: { + outcome: { + reverse_nested: {}, + aggs: { + count: { + terms: { + field: 'event.outcome', }, }, }, @@ -590,28 +582,28 @@ export async function getExecutionsPerDayCount( }); const aggsExecutions = getActionExecutions( - // @ts-expect-error aggegation type is not specified + // @ts-expect-error aggregation type is not specified actionResults.aggregations.totalExecutions?.refs?.byConnectorTypeId.buckets ); // convert nanoseconds to milliseconds const aggsAvgExecutionTime = Math.round( - // @ts-expect-error aggegation type is not specified + // @ts-expect-error aggregation type is not specified actionResults.aggregations.avgDuration.value / (1000 * 1000) ); const aggsFailedExecutions = getActionExecutions( - // @ts-expect-error aggegation type is not specified + // @ts-expect-error aggregation type is not specified actionResults.aggregations.failedExecutions?.actionSavedObjects?.refs?.byConnectorTypeId .buckets ); const avgDurationByType = - // @ts-expect-error aggegation type is not specified + // @ts-expect-error aggregation type is not specified actionResults.aggregations.avgDurationByType?.actionSavedObjects?.byTypeId?.buckets; const avgExecutionTimeByType: Record = avgDurationByType.reduce( - // @ts-expect-error aggegation type is not specified + // @ts-expect-error aggregation type is not specified (res: Record, bucket) => { res[replaceFirstAndLastDotSymbols(bucket.key)] = bucket?.refs.avgDuration.value; return res; diff --git a/x-pack/platform/plugins/shared/actions/server/usage/lib/parse_connector_type_bucket.ts b/x-pack/platform/plugins/shared/actions/server/usage/lib/parse_connector_type_bucket.ts index 96e1610c635d8..936dc3f217ca2 100644 --- a/x-pack/platform/plugins/shared/actions/server/usage/lib/parse_connector_type_bucket.ts +++ b/x-pack/platform/plugins/shared/actions/server/usage/lib/parse_connector_type_bucket.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AggregationsBuckets } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsBuckets } from '@elastic/elasticsearch/lib/api/types'; import { replaceFirstAndLastDotSymbols } from '../actions_telemetry'; export interface AvgActionRunOutcomeByConnectorTypeBucket { diff --git a/x-pack/platform/plugins/shared/aiops/public/application/url_state/common.ts b/x-pack/platform/plugins/shared/aiops/public/application/url_state/common.ts index eb037dabb9648..32aeed6b56221 100644 --- a/x-pack/platform/plugins/shared/aiops/public/application/url_state/common.ts +++ b/x-pack/platform/plugins/shared/aiops/public/application/url_state/common.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Filter, Query } from '@kbn/es-query'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/plugins/shared/aiops/public/application/utils/build_extended_base_filter_criteria.ts b/x-pack/platform/plugins/shared/aiops/public/application/utils/build_extended_base_filter_criteria.ts index c4b92ac028d0b..7222ede7808ef 100644 --- a/x-pack/platform/plugins/shared/aiops/public/application/utils/build_extended_base_filter_criteria.ts +++ b/x-pack/platform/plugins/shared/aiops/public/application/utils/build_extended_base_filter_criteria.ts @@ -8,7 +8,7 @@ // TODO Consolidate with duplicate query utils in // `x-pack/platform/plugins/private/data_visualizer/common/utils/query_utils.ts` -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Query } from '@kbn/es-query'; import { type SignificantItem, SIGNIFICANT_ITEM_TYPE } from '@kbn/ml-agg-utils'; diff --git a/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts b/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts index 718b63a0069d0..0cd0fcddd4b74 100644 --- a/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts +++ b/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts @@ -16,7 +16,7 @@ import type { FilterManager } from '@kbn/data-plugin/public'; import { mapAndFlattenFilters } from '@kbn/data-plugin/public'; import type { Query, Filter } from '@kbn/es-query'; import { buildEsQuery } from '@kbn/es-query'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { DataView } from '@kbn/data-views-plugin/public'; import type { SimpleSavedObject } from '@kbn/core/public'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_change_point_agg_request.ts b/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_change_point_agg_request.ts index 19a724400a454..e9745caf8daa0 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_change_point_agg_request.ts +++ b/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_change_point_agg_request.ts @@ -9,10 +9,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { type QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { isDefined } from '@kbn/ml-is-defined'; -import type { - MappingRuntimeFields, - SearchRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields, SearchRequest } from '@elastic/elasticsearch/lib/api/types'; import { METRIC_TYPE } from '@kbn/analytics'; import { useReload } from '../../hooks/use_reload'; import { useAiopsAppContext } from '../../hooks/use_aiops_app_context'; @@ -108,11 +105,9 @@ function getChangePointDetectionRequestBody( return { index, size: 0, - body: { - ...(query ? { query } : {}), - ...(runtimeMappings ? { runtime_mappings: runtimeMappings } : {}), - aggregations, - }, + ...(query ? { query } : {}), + ...(runtimeMappings ? { runtime_mappings: runtimeMappings } : {}), + aggregations, } as SearchRequest; } diff --git a/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_split_field_cardinality.ts b/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_split_field_cardinality.ts index 91d764e0d7d95..3ced2bd880d2d 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_split_field_cardinality.ts +++ b/x-pack/platform/plugins/shared/aiops/public/components/change_point_detection/use_split_field_cardinality.ts @@ -43,17 +43,15 @@ export function useSplitFieldCardinality( params: { index: dataView.getIndexPattern(), size: 0, - body: { - query, - aggregations: { - fieldCount: { - cardinality: { - field: splitField, - }, + query, + aggregations: { + fieldCount: { + cardinality: { + field: splitField, }, }, - ...runtimeMappings, }, + ...runtimeMappings, }, }; }, [splitField, dataView, query, splitFieldsOptions]); diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/create_categorization_job.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/create_categorization_job.tsx index 91a3185b683bb..235f57aed4931 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/create_categorization_job.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/create_categorization_job.tsx @@ -11,7 +11,7 @@ import React from 'react'; import moment from 'moment'; import { EuiButtonEmpty, EuiButtonIcon, EuiToolTip } from '@elastic/eui'; import type { DataViewField, DataView } from '@kbn/data-views-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { CREATE_PATTERN_ANALYSIS_TO_ML_AD_JOB_TRIGGER, type CreateCategorizationADJobContext, diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/discover_tabs.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/discover_tabs.tsx index 8eff41152c00a..2989848649a63 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/discover_tabs.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/discover_tabs.tsx @@ -13,7 +13,7 @@ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import type { Category } from '@kbn/aiops-log-pattern-analysis/types'; import type { DataViewField, DataView } from '@kbn/data-views-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { OpenInDiscover } from '../category_table/use_open_in_discover'; import { EmbeddableMenu } from './embeddable_menu'; import type { RandomSampler } from '../sampling_menu'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/use_minimum_time_range.ts b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/use_minimum_time_range.ts index 50328a2ef345c..30e48d06fcb8a 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/use_minimum_time_range.ts +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_for_embeddable/use_minimum_time_range.ts @@ -12,7 +12,7 @@ import type { HttpFetchOptions } from '@kbn/core/public'; import { getTimeFieldRange } from '@kbn/ml-date-picker'; import moment from 'moment'; import { useStorage } from '@kbn/ml-local-storage'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import { useAiopsAppContext } from '../../../hooks/use_aiops_app_context'; import type { MinimumTimeRangeOption } from './minimum_time_range'; import { DEFAULT_MINIMUM_TIME_RANGE_OPTION, MINIMUM_TIME_RANGE } from './minimum_time_range'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx index 482ef5801183d..4222bdb17e032 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useState, useEffect, useCallback, useMemo } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; import { EuiHorizontalRule } from '@elastic/eui'; import { diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_categorize_request.ts b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_categorize_request.ts index 1c792c4f484a6..69ab71d4f9ae2 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_categorize_request.ts +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_categorize_request.ts @@ -18,7 +18,7 @@ import { import { processCategoryResults } from '@kbn/aiops-log-pattern-analysis/process_category_results'; import type { CatResponse } from '@kbn/aiops-log-pattern-analysis/types'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import { useAiopsAppContext } from '../../hooks/use_aiops_app_context'; import type { RandomSamplerStorage } from './sampling_menu'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_validate_category_field.ts b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_validate_category_field.ts index 571bb3d1e0f87..3eb2b8370522f 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_validate_category_field.ts +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/use_validate_category_field.ts @@ -8,7 +8,7 @@ import { useRef, useCallback } from 'react'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import type { FieldValidationResults } from '@kbn/ml-category-validator'; import type { HttpFetchOptions } from '@kbn/core/public'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx index 37b3d796f4891..38e10d585f755 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx @@ -9,7 +9,7 @@ import { isEqual } from 'lodash'; import React, { useCallback, useEffect, useMemo, useRef, type FC } from 'react'; import { EuiButton, EuiEmptyPrompt, EuiSpacer, EuiPanel } from '@elastic/eui'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { BarStyleAccessor } from '@elastic/charts/dist/chart_types/xy_chart/utils/specs'; import { FormattedMessage } from '@kbn/i18n-react'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content_wrapper.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content_wrapper.tsx index 358224d990854..3c68a2e3c2fa4 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content_wrapper.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content_wrapper.tsx @@ -9,7 +9,7 @@ import React, { type FC } from 'react'; import { pick } from 'lodash'; import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { WindowParameters } from '@kbn/aiops-log-rate-analysis'; import type { DataView } from '@kbn/data-views-plugin/public'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_document_count_chart_data.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_document_count_chart_data.tsx index 7709c047fd6ae..2c091690831d3 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_document_count_chart_data.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_document_count_chart_data.tsx @@ -8,7 +8,7 @@ import { type FC, useEffect } from 'react'; import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useAppDispatch, diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx index 403434c51bb0f..c499cc0c87467 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx @@ -9,7 +9,7 @@ import type { FC } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { isEqual, orderBy } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiFlexGroup, EuiFlexItem, EuiPageBody, EuiPageSection, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_results.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_results.tsx index 42fa509e6ce40..bb7f4c442b085 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_results.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_results.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useEffect, useMemo, useRef, useState } from 'react'; import { isEqual } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiButtonIcon, diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx index 816d7654444e4..609c7c25ec894 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { orderBy, isEqual } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Criteria, EuiTableSortingType } from '@elastic/eui'; import { useEuiTheme, useEuiBackgroundColor, EuiBasicTable } from '@elastic/eui'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table_groups.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table_groups.tsx index ceeeb79c1232c..57bc7bc40810b 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table_groups.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/log_rate_analysis_results_table_groups.tsx @@ -24,7 +24,7 @@ import { euiPaletteColorBlind, } from '@elastic/eui'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import { type SignificantItem } from '@kbn/ml-agg-utils'; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx index a9657c907f938..2fef0af9dad33 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis_results_table/use_columns.tsx @@ -15,7 +15,7 @@ import { EuiIconTip, EuiText, } from '@elastic/eui'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import { type SignificantItem, SIGNIFICANT_ITEM_TYPE } from '@kbn/ml-agg-utils'; diff --git a/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts b/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts index 430c914c3cf58..a23a750f5f3f3 100644 --- a/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts +++ b/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import dateMath from '@kbn/datemath'; import { getExtendedChangePoint, type DocumentCountStats } from '@kbn/aiops-log-rate-analysis'; diff --git a/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts b/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts index 9d54dfaac1eaf..a73ced70d4c8a 100644 --- a/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts +++ b/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts @@ -9,7 +9,7 @@ import { useEffect, useMemo, useState } from 'react'; import { merge } from 'rxjs'; import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useExecutionContext } from '@kbn/kibana-react-plugin/public'; import type { DataView } from '@kbn/data-views-plugin/public'; diff --git a/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts b/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts index a21b7a3e4a0d0..34949dcae902d 100644 --- a/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts +++ b/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts @@ -8,7 +8,7 @@ import { chunk } from 'lodash'; import { queue } from 'async'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import type { diff --git a/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/overall_histogram_handler.ts b/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/overall_histogram_handler.ts index 01f1972831b65..4bb0b8f2c5e26 100644 --- a/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/overall_histogram_handler.ts +++ b/x-pack/platform/plugins/shared/aiops/server/routes/log_rate_analysis/analysis_handlers/overall_histogram_handler.ts @@ -46,11 +46,8 @@ export const overallHistogramHandlerFactory = { index: requestBody.index, size: 0, - body: { - query: overallHistogramQuery, - aggs: wrap(miniHistogramAgg), - size: 0, - }, + query: overallHistogramQuery, + aggs: wrap(miniHistogramAgg), }, { signal: abortSignal, maxRetries: 0 } ); diff --git a/x-pack/platform/plugins/shared/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts b/x-pack/platform/plugins/shared/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts index 1d5121883df69..67e41f6d9de6c 100644 --- a/x-pack/platform/plugins/shared/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts +++ b/x-pack/platform/plugins/shared/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { set } from '@kbn/safer-lodash-set'; import type { FieldMap, MultiField } from '@kbn/alerts-as-data-utils'; diff --git a/x-pack/platform/plugins/shared/alerting/common/rule_tags_aggregation.ts b/x-pack/platform/plugins/shared/alerting/common/rule_tags_aggregation.ts index 4df444d51e19b..bfdc244e9e116 100644 --- a/x-pack/platform/plugins/shared/alerting/common/rule_tags_aggregation.ts +++ b/x-pack/platform/plugins/shared/alerting/common/rule_tags_aggregation.ts @@ -8,7 +8,7 @@ import type { AggregationsAggregationContainer, AggregationsCompositeAggregation, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { AggregateOptions } from '../server/application/rule/methods/aggregate/types'; export type RuleTagsAggregationOptions = Pick & { diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.test.ts index 557341f3e02de..1dcb79ed1009e 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.test.ts @@ -442,18 +442,16 @@ describe('Alerts Client', () => { ); expect(clusterClient.search).toHaveBeenCalledWith({ - body: { - query: { - bool: { - filter: [ - { term: { 'kibana.alert.rule.uuid': '1' } }, - { terms: { 'kibana.alert.uuid': ['abc', 'def', 'xyz'] } }, - ], - }, + query: { + bool: { + filter: [ + { term: { 'kibana.alert.rule.uuid': '1' } }, + { terms: { 'kibana.alert.uuid': ['abc', 'def', 'xyz'] } }, + ], }, - seq_no_primary_term: true, - size: 3, }, + seq_no_primary_term: true, + size: 3, index: useDataStreamForAlerts ? '.alerts-test.alerts-default' : '.internal.alerts-test.alerts-default-*', @@ -516,18 +514,16 @@ describe('Alerts Client', () => { ); expect(clusterClient.search).toHaveBeenCalledWith({ - body: { - query: { - bool: { - filter: [ - { term: { 'kibana.alert.rule.uuid': '1' } }, - { terms: { 'kibana.alert.uuid': ['abc'] } }, - ], - }, + query: { + bool: { + filter: [ + { term: { 'kibana.alert.rule.uuid': '1' } }, + { terms: { 'kibana.alert.uuid': ['abc'] } }, + ], }, - size: 1, - seq_no_primary_term: true, }, + size: 1, + seq_no_primary_term: true, index: useDataStreamForAlerts ? '.alerts-test.alerts-default' : '.internal.alerts-test.alerts-default-*', diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.ts index baf786177ba01..765f59f72eb6e 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client.ts @@ -15,7 +15,7 @@ import { ALERT_MAINTENANCE_WINDOW_IDS, } from '@kbn/rule-data-utils'; import { chunk, flatMap, get, isEmpty, keys } from 'lodash'; -import { SearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { Alert } from '@kbn/alerts-as-data-utils'; import { DEFAULT_NAMESPACE_STRING } from '@kbn/core-saved-objects-utils-server'; import { DeepPartial } from '@kbn/utility-types'; @@ -231,7 +231,7 @@ export class AlertsClient< } public async search( - queryBody: SearchRequest['body'] + queryBody: SearchRequest ): Promise> { const esClient = await this.options.elasticsearchClientPromise; const index = this.isUsingDataStreams() @@ -242,7 +242,7 @@ export class AlertsClient< aggregations, } = await esClient.search({ index, - body: queryBody, + ...queryBody, ignore_unavailable: true, }); diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client_fixtures.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client_fixtures.ts index db666e5501975..7f65cf89e527f 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client_fixtures.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/alerts_client_fixtures.ts @@ -129,67 +129,66 @@ export const getExpectedQueryByExecutionUuid = ({ excludedAlertInstanceIds?: string[]; alertsFilter?: AlertsFilter; }) => ({ - body: { - query: { - bool: { - filter: [ - { term: { 'kibana.alert.rule.execution.uuid': uuid } }, - { term: { 'kibana.alert.rule.uuid': ruleId } }, - { - bool: { must_not: { exists: { field: 'kibana.alert.maintenance_window_ids' } } }, - }, - ...(isLifecycleAlert ? [{ term: { 'event.action': alertTypes[alertType] } }] : []), - ...(!!excludedAlertInstanceIds?.length - ? [ - { - bool: { - must_not: { - terms: { - 'kibana.alert.instance.id': excludedAlertInstanceIds, - }, + query: { + bool: { + filter: [ + { term: { 'kibana.alert.rule.execution.uuid': uuid } }, + { term: { 'kibana.alert.rule.uuid': ruleId } }, + { + bool: { must_not: { exists: { field: 'kibana.alert.maintenance_window_ids' } } }, + }, + ...(isLifecycleAlert ? [{ term: { 'event.action': alertTypes[alertType] } }] : []), + ...(!!excludedAlertInstanceIds?.length + ? [ + { + bool: { + must_not: { + terms: { + 'kibana.alert.instance.id': excludedAlertInstanceIds, }, }, }, - ] - : []), - ...(alertsFilter - ? [ - { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - [alertsFilter.query!.kql.split(':')[0]]: - alertsFilter.query!.kql.split(':')[1], - }, + }, + ] + : []), + ...(alertsFilter + ? [ + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + [alertsFilter.query!.kql.split(':')[0]]: + alertsFilter.query!.kql.split(':')[1], }, - ], - }, + }, + ], }, - { + }, + { + script: { script: { - script: { - params: { - datetimeField: '@timestamp', - days: alertsFilter.timeframe?.days, - timezone: alertsFilter.timeframe!.timezone, - }, - source: - 'params.days.contains(doc[params.datetimeField].value.withZoneSameInstant(ZoneId.of(params.timezone)).dayOfWeek.getValue())', + params: { + datetimeField: '@timestamp', + days: alertsFilter.timeframe?.days, + timezone: alertsFilter.timeframe!.timezone, }, + source: + 'params.days.contains(doc[params.datetimeField].value.withZoneSameInstant(ZoneId.of(params.timezone)).dayOfWeek.getValue())', }, }, - { + }, + { + script: { script: { - script: { - params: { - datetimeField: '@timestamp', - end: alertsFilter.timeframe!.hours.end, - start: alertsFilter.timeframe!.hours.start, - timezone: alertsFilter.timeframe!.timezone, - }, - source: ` + params: { + datetimeField: '@timestamp', + end: alertsFilter.timeframe!.hours.end, + start: alertsFilter.timeframe!.hours.start, + timezone: alertsFilter.timeframe!.timezone, + }, + source: ` def alertsDateTime = doc[params.datetimeField].value.withZoneSameInstant(ZoneId.of(params.timezone)); def alertsTime = LocalTime.of(alertsDateTime.getHour(), alertsDateTime.getMinute()); def start = LocalTime.parse(params.start); @@ -211,17 +210,16 @@ export const getExpectedQueryByExecutionUuid = ({ } } `, - }, }, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, - size: 1000, - track_total_hits: true, }, + size: 1000, + track_total_hits: true, ignore_unavailable: true, index: indexName, }); @@ -376,15 +374,13 @@ export const getExpectedQueryByTimeRange = ({ } return { - body: { - query: { - bool: { - filter, - }, + query: { + bool: { + filter, }, - size: 1000, - track_total_hits: true, }, + size: 1000, + track_total_hits: true, ignore_unavailable: true, index: indexName, }; diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/get_summarized_alerts_query.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/get_summarized_alerts_query.ts index 75d6780880beb..cbad081b05961 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/get_summarized_alerts_query.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/get_summarized_alerts_query.ts @@ -10,7 +10,7 @@ import { SearchRequest, SearchTotalHits, AggregationsAggregationContainer, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { BoolQuery } from '@kbn/es-query'; import { ALERT_END, @@ -53,7 +53,7 @@ const getLifecycleAlertsQueryByExecutionUuid = ({ excludedAlertInstanceIds, alertsFilter, maxAlertLimit, -}: GetLifecycleAlertsQueryByExecutionUuidParams): Array => { +}: GetLifecycleAlertsQueryByExecutionUuidParams): SearchRequest[] => { // lifecycle alerts assign a different action to an alert depending // on whether it is new/ongoing/recovered. query for each action in order // to get the count of each action type as well as up to the maximum number @@ -93,7 +93,7 @@ const getLifecycleAlertsQueryByTimeRange = ({ excludedAlertInstanceIds, alertsFilter, maxAlertLimit, -}: GetLifecycleAlertsQueryByTimeRangeParams): Array => { +}: GetLifecycleAlertsQueryByTimeRangeParams): SearchRequest[] => { return [ getQueryByTimeRange({ start, @@ -132,7 +132,7 @@ const getQueryByExecutionUuid = ({ action, alertsFilter, maxAlertLimit, -}: GetQueryByExecutionUuidParams): SearchRequest['body'] => { +}: GetQueryByExecutionUuidParams): SearchRequest => { const filter: QueryDslQueryContainer[] = [ { term: { @@ -196,7 +196,7 @@ const getQueryByTimeRange = ({ type, alertsFilter, maxAlertLimit, -}: GetQueryByTimeRangeParams): SearchRequest['body'] => { +}: GetQueryByTimeRangeParams): SearchRequest => { // base query filters the alert documents for a rule by the given time range let filter: QueryDslQueryContainer[] = [ { @@ -292,7 +292,7 @@ export const getQueryByScopedQueries = ({ action, maintenanceWindows, maxAlertLimit, -}: GetQueryByScopedQueriesParams): SearchRequest['body'] => { +}: GetQueryByScopedQueriesParams): SearchRequest => { const filters: QueryDslQueryContainer[] = [ { term: { @@ -471,7 +471,7 @@ const getLifecycleAlertsQueries = ({ excludedAlertInstanceIds, alertsFilter, maxAlertLimit, -}: GetAlertsQueryParams): Array => { +}: GetAlertsQueryParams): SearchRequest[] => { let queryBodies; if (!!executionUuid) { queryBodies = getLifecycleAlertsQueryByExecutionUuid({ @@ -503,7 +503,7 @@ const getContinualAlertsQuery = ({ excludedAlertInstanceIds, alertsFilter, maxAlertLimit, -}: GetAlertsQueryParams): SearchRequest['body'] => { +}: GetAlertsQueryParams): SearchRequest => { let queryBody; if (!!executionUuid) { queryBody = getQueryByExecutionUuid({ @@ -533,7 +533,7 @@ const getMaintenanceWindowAlertsQuery = ({ action, maintenanceWindows, maxAlertLimit, -}: GetMaintenanceWindowAlertsQueryParams): SearchRequest['body'] => { +}: GetMaintenanceWindowAlertsQueryParams): SearchRequest => { return getQueryByScopedQueries({ executionUuid, ruleId, diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/inject_analyze_wildcard.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/inject_analyze_wildcard.ts index 58a4f89948973..2a6f6a3e0b754 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/inject_analyze_wildcard.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/inject_analyze_wildcard.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; export const injectAnalyzeWildcard = (query: QueryDslQueryContainer): void => { if (!query) { diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.test.ts index 533bb5b554ae9..ec0211646a1be 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.test.ts @@ -5,7 +5,7 @@ * 2.0. */ import { TransportResult } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { sanitizeBulkErrorResponse } from './sanitize_bulk_response'; // Using https://www.elastic.co/guide/en/elasticsearch/reference/8.11/docs-bulk.html diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.ts index 0c18500c3bd5f..0c79b6e2e13f1 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/sanitize_bulk_response.ts @@ -8,7 +8,7 @@ import { cloneDeep } from 'lodash'; import { TransportResult } from '@elastic/elasticsearch'; import { get } from 'lodash'; import { set } from '@kbn/safer-lodash-set'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export const sanitizeBulkErrorResponse = ( response: TransportResult | estypes.BulkResponse diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/alerts_service.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/alerts_service.test.ts index 71285471c363e..51fe6e8608514 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/alerts_service.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/alerts_service.test.ts @@ -10,7 +10,7 @@ import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-m import { IndicesGetDataStreamResponse, IndicesDataStreamIndex, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { errors as EsErrors } from '@elastic/elasticsearch'; import { ReplaySubject, Subject, of } from 'rxjs'; import { AlertsService } from './alerts_service'; @@ -150,54 +150,52 @@ const getIndexTemplatePutBody = (opts?: GetIndexTemplatePutBodyOpts) => { ]; return { name: `.alerts-${context ? context : 'test'}.alerts-${namespace}-index-template`, - body: { - index_patterns: indexPatterns, - composed_of: [ - ...(useEcs ? ['.alerts-ecs-mappings'] : []), - `.alerts-${context ? `${context}.alerts` : 'test.alerts'}-mappings`, - ...(useLegacyAlerts ? ['.alerts-legacy-alert-mappings'] : []), - '.alerts-framework-mappings', - ], - ...(useDataStream ? { data_stream: { hidden: true } } : {}), - priority: namespace.length, - template: { - settings: { - auto_expand_replicas: '0-1', - hidden: true, - ...(useDataStream - ? {} - : { - 'index.lifecycle': { - name: '.alerts-ilm-policy', - rollover_alias: `.alerts-${context ? context : 'test'}.alerts-${namespace}`, - }, - }), - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': 2500, - }, - mappings: { - dynamic: false, - _meta: { - kibana: { version: '8.8.0' }, - managed: true, - namespace, - }, - }, - ...(secondaryAlias - ? { - aliases: { - [`${secondaryAlias}-default`]: { - is_write_index: false, - }, + index_patterns: indexPatterns, + composed_of: [ + ...(useEcs ? ['.alerts-ecs-mappings'] : []), + `.alerts-${context ? `${context}.alerts` : 'test.alerts'}-mappings`, + ...(useLegacyAlerts ? ['.alerts-legacy-alert-mappings'] : []), + '.alerts-framework-mappings', + ], + ...(useDataStream ? { data_stream: { hidden: true } } : {}), + priority: namespace.length, + template: { + settings: { + auto_expand_replicas: '0-1', + hidden: true, + ...(useDataStream + ? {} + : { + 'index.lifecycle': { + name: '.alerts-ilm-policy', + rollover_alias: `.alerts-${context ? context : 'test'}.alerts-${namespace}`, }, - } - : {}), + }), + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': 2500, }, - _meta: { - kibana: { version: '8.8.0' }, - managed: true, - namespace, + mappings: { + dynamic: false, + _meta: { + kibana: { version: '8.8.0' }, + managed: true, + namespace, + }, }, + ...(secondaryAlias + ? { + aliases: { + [`${secondaryAlias}-default`]: { + is_write_index: false, + }, + }, + } + : {}), + }, + _meta: { + kibana: { version: '8.8.0' }, + managed: true, + namespace, }, }; }; @@ -558,11 +556,9 @@ describe('Alerts Service', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -624,11 +620,9 @@ describe('Alerts Service', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -686,11 +680,9 @@ describe('Alerts Service', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -731,11 +723,9 @@ describe('Alerts Service', () => { } else { expect(clusterClient.indices.create).toHaveBeenNthCalledWith(1, { index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -798,11 +788,9 @@ describe('Alerts Service', () => { } else { expect(clusterClient.indices.create).toHaveBeenNthCalledWith(2, { index: '.internal.alerts-test.alerts-another-namespace-000001', - body: { - aliases: { - '.alerts-test.alerts-another-namespace': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-another-namespace': { + is_write_index: true, }, }, }); @@ -855,11 +843,9 @@ describe('Alerts Service', () => { expect(clusterClient.indices.putMapping).toHaveBeenCalledTimes(2); expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -891,46 +877,44 @@ describe('Alerts Service', () => { const template = { name: `.alerts-empty.alerts-default-index-template`, - body: { - index_patterns: useDataStreamForAlerts - ? [`.alerts-empty.alerts-default`] - : [ - `.internal.alerts-empty.alerts-default-*`, - `.reindexed-v8-internal.alerts-empty.alerts-default-*`, - ], - composed_of: ['.alerts-framework-mappings'], - ...(useDataStreamForAlerts ? { data_stream: { hidden: true } } : {}), - priority: 7, - template: { - settings: { - auto_expand_replicas: '0-1', - hidden: true, - ...(useDataStreamForAlerts - ? {} - : { - 'index.lifecycle': { - name: '.alerts-ilm-policy', - rollover_alias: `.alerts-empty.alerts-default`, - }, - }), - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': 2500, - }, - mappings: { - _meta: { - kibana: { version: '8.8.0' }, - managed: true, - namespace: 'default', - }, - dynamic: false, - }, + index_patterns: useDataStreamForAlerts + ? [`.alerts-empty.alerts-default`] + : [ + `.internal.alerts-empty.alerts-default-*`, + `.reindexed-v8-internal.alerts-empty.alerts-default-*`, + ], + composed_of: ['.alerts-framework-mappings'], + ...(useDataStreamForAlerts ? { data_stream: { hidden: true } } : {}), + priority: 7, + template: { + settings: { + auto_expand_replicas: '0-1', + hidden: true, + ...(useDataStreamForAlerts + ? {} + : { + 'index.lifecycle': { + name: '.alerts-ilm-policy', + rollover_alias: `.alerts-empty.alerts-default`, + }, + }), + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': 2500, }, - _meta: { - kibana: { version: '8.8.0' }, - managed: true, - namespace: 'default', + mappings: { + _meta: { + kibana: { version: '8.8.0' }, + managed: true, + namespace: 'default', + }, + dynamic: false, }, }, + _meta: { + kibana: { version: '8.8.0' }, + managed: true, + namespace: 'default', + }, }; expect(clusterClient.indices.putIndexTemplate).toHaveBeenCalledWith(template); @@ -944,11 +928,9 @@ describe('Alerts Service', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-empty.alerts-default-000001', - body: { - aliases: { - '.alerts-empty.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-empty.alerts-default': { + is_write_index: true, }, }, }); diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/default_lifecycle_policy.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/default_lifecycle_policy.ts index 67230f1c35da0..e6717f408b342 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/default_lifecycle_policy.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/default_lifecycle_policy.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { IlmPolicy } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { IlmPolicy } from '@elastic/elasticsearch/lib/api/types'; /** * Default alert index ILM policy diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.test.ts index f8e2f8c089529..2683007ca86f4 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.test.ts @@ -6,7 +6,7 @@ */ import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { errors as EsErrors } from '@elastic/elasticsearch'; -import { IndicesGetDataStreamResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { IndicesGetDataStreamResponse } from '@elastic/elasticsearch/lib/api/types'; import { createConcreteWriteIndex, setConcreteWriteIndex } from './create_concrete_write_index'; import { getDataStreamAdapter } from './data_stream_adapter'; @@ -95,11 +95,9 @@ describe('createConcreteWriteIndex', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -309,11 +307,9 @@ describe('createConcreteWriteIndex', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -359,11 +355,9 @@ describe('createConcreteWriteIndex', () => { if (!useDataStream) { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -399,11 +393,9 @@ describe('createConcreteWriteIndex', () => { if (!useDataStream) { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -631,11 +623,9 @@ describe('createConcreteWriteIndex', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -670,11 +660,9 @@ describe('createConcreteWriteIndex', () => { } else { expect(clusterClient.indices.create).toHaveBeenCalledWith({ index: '.internal.alerts-test.alerts-default-000001', - body: { - aliases: { - '.alerts-test.alerts-default': { - is_write_index: true, - }, + aliases: { + '.alerts-test.alerts-default': { + is_write_index: true, }, }, }); @@ -756,23 +744,21 @@ describe('setConcreteWriteIndex', () => { 'Attempting to set index: .internal.alerts-test.alerts-default-000004 as the write index for alias: .alerts-test.alerts-default.' ); expect(clusterClient.indices.updateAliases).toHaveBeenCalledWith({ - body: { - actions: [ - { - remove: { - alias: '.alerts-test.alerts-default', - index: '.internal.alerts-test.alerts-default-000004', - }, + actions: [ + { + remove: { + alias: '.alerts-test.alerts-default', + index: '.internal.alerts-test.alerts-default-000004', }, - { - add: { - alias: '.alerts-test.alerts-default', - index: '.internal.alerts-test.alerts-default-000004', - is_write_index: true, - }, + }, + { + add: { + alias: '.alerts-test.alerts-default', + index: '.internal.alerts-test.alerts-default-000004', + is_write_index: true, }, - ], - }, + }, + ], }); expect(logger.info).toHaveBeenCalledWith( 'Successfully set index: .internal.alerts-test.alerts-default-000004 as the write index for alias: .alerts-test.alerts-default.' diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.ts index cc298ed3cd7d2..672aee63c7a80 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_concrete_write_index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { IndicesSimulateIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { IndicesSimulateIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/types'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; import { get, sortBy } from 'lodash'; import { IIndexPatternString } from '../resource_installer_utils'; @@ -45,7 +45,7 @@ const updateTotalFieldLimitSetting = async ({ () => esClient.indices.putSettings({ index, - body: { 'index.mapping.total_fields.limit': totalFieldsLimit }, + settings: { 'index.mapping.total_fields.limit': totalFieldsLimit }, }), { logger } ); @@ -90,6 +90,7 @@ const updateUnderlyingMapping = async ({ try { await retryTransientEsErrors( + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 () => esClient.indices.putMapping({ index, body: simulatedMapping }), { logger } ); @@ -183,18 +184,16 @@ export async function setConcreteWriteIndex(opts: SetConcreteWriteIndexOpts) { await retryTransientEsErrors( () => esClient.indices.updateAliases({ - body: { - actions: [ - { remove: { index: concreteIndex.index, alias: concreteIndex.alias } }, - { - add: { - index: concreteIndex.index, - alias: concreteIndex.alias, - is_write_index: true, - }, + actions: [ + { remove: { index: concreteIndex.index, alias: concreteIndex.alias } }, + { + add: { + index: concreteIndex.index, + alias: concreteIndex.alias, + is_write_index: true, }, - ], - }, + }, + ], }), { logger } ); diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.test.ts index 3a1d490afe9d6..54f02fd687359 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.test.ts @@ -8,12 +8,13 @@ import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mo import { errors as EsErrors } from '@elastic/elasticsearch'; import { createOrUpdateComponentTemplate } from './create_or_update_component_template'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; +import { ClusterPutComponentTemplateRequest } from '@elastic/elasticsearch/lib/api/types'; const randomDelayMultiplier = 0.01; const logger = loggingSystemMock.createLogger(); const clusterClient = elasticsearchServiceMock.createClusterClient().asInternalUser; -const ComponentTemplate = { +const ComponentTemplate: ClusterPutComponentTemplateRequest = { name: 'test-mappings', _meta: { managed: true, diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.ts index 9a18c3eb8a84e..d9485c95b006e 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_component_template.ts @@ -8,8 +8,7 @@ import { ClusterPutComponentTemplateRequest, IndicesGetIndexTemplateIndexTemplateItem, - type IndicesPutIndexTemplateRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; import { asyncForEach } from '@kbn/std'; import { retryTransientEsErrors } from './retry_transient_es_errors'; @@ -53,6 +52,7 @@ const getIndexTemplatesUsingComponentTemplate = async ( name: template.name, body: { ...template.index_template, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 template: { ...template.index_template.template, settings: { @@ -60,7 +60,7 @@ const getIndexTemplatesUsingComponentTemplate = async ( 'index.mapping.total_fields.limit': totalFieldsLimit, }, }, - } as IndicesPutIndexTemplateRequest['body'], + }, }), { logger } ); diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_ilm_policy.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_ilm_policy.ts index 4ba14dbe3956b..aabdfbf5dde52 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_ilm_policy.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_ilm_policy.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { IlmPolicy } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { IlmPolicy } from '@elastic/elasticsearch/lib/api/types'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; import { retryTransientEsErrors } from './retry_transient_es_errors'; import { DataStreamAdapter } from './data_stream_adapter'; diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.test.ts index 85113b768860a..b130976f6bcb0 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.test.ts @@ -16,44 +16,42 @@ const clusterClient = elasticsearchServiceMock.createClusterClient().asInternalU const IndexTemplate = (namespace: string = 'default', useDataStream: boolean = false) => ({ name: `.alerts-test.alerts-${namespace}-index-template`, - body: { - _meta: { - kibana: { - version: '8.6.1', - }, - managed: true, - namespace, + _meta: { + kibana: { + version: '8.6.1', }, - composed_of: ['mappings1', 'framework-mappings'], - index_patterns: [`.internal.alerts-test.alerts-${namespace}-*`], - template: { - mappings: { - _meta: { - kibana: { - version: '8.6.1', - }, - managed: true, - namespace, + managed: true, + namespace, + }, + composed_of: ['mappings1', 'framework-mappings'], + index_patterns: [`.internal.alerts-test.alerts-${namespace}-*`], + template: { + mappings: { + _meta: { + kibana: { + version: '8.6.1', }, - dynamic: false, - }, - settings: { - auto_expand_replicas: '0-1', - hidden: true, - ...(useDataStream - ? {} - : { - 'index.lifecycle': { - name: 'test-ilm-policy', - rollover_alias: `.alerts-test.alerts-${namespace}`, - }, - }), - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': 2500, + managed: true, + namespace, }, + dynamic: false, + }, + settings: { + auto_expand_replicas: '0-1', + hidden: true, + ...(useDataStream + ? {} + : { + 'index.lifecycle': { + name: 'test-ilm-policy', + rollover_alias: `.alerts-test.alerts-${namespace}`, + }, + }), + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': 2500, }, - priority: namespace.length, }, + priority: namespace.length, }); const SimulateTemplateResponse = { diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.ts index 0a1b4951bcc9a..d54d9cd09572a 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/create_or_update_index_template.ts @@ -9,7 +9,7 @@ import { IndicesPutIndexTemplateRequest, MappingTypeMapping, Metadata, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; import { isEmpty } from 'lodash'; import { IIndexPatternString } from '../resource_installer_utils'; @@ -57,42 +57,40 @@ export const getIndexTemplate = ({ return { name: indexPatterns.template, - body: { - ...(dataStreamFields.data_stream ? { data_stream: dataStreamFields.data_stream } : {}), - index_patterns: dataStreamFields.index_patterns, - composed_of: componentTemplateRefs, - template: { - settings: { - auto_expand_replicas: '0-1', - hidden: true, - ...(dataStreamAdapter.isUsingDataStreams() - ? {} - : { - 'index.lifecycle': indexLifecycle, - }), - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': totalFieldsLimit, - }, - mappings: { - dynamic: false, - _meta: indexMetadata, - }, - ...(indexPatterns.secondaryAlias - ? { - aliases: { - [indexPatterns.secondaryAlias]: { - is_write_index: false, - }, - }, - } - : {}), + ...(dataStreamFields.data_stream ? { data_stream: dataStreamFields.data_stream } : {}), + index_patterns: dataStreamFields.index_patterns, + composed_of: componentTemplateRefs, + template: { + settings: { + auto_expand_replicas: '0-1', + hidden: true, + ...(dataStreamAdapter.isUsingDataStreams() + ? {} + : { + 'index.lifecycle': indexLifecycle, + }), + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': totalFieldsLimit, }, - _meta: indexMetadata, - - // By setting the priority to namespace.length, we ensure that if one namespace is a prefix of another namespace - // then newly created indices will use the matching template with the *longest* namespace - priority: namespace.length, + mappings: { + dynamic: false, + _meta: indexMetadata, + }, + ...(indexPatterns.secondaryAlias + ? { + aliases: { + [indexPatterns.secondaryAlias]: { + is_write_index: false, + }, + }, + } + : {}), }, + _meta: indexMetadata, + + // By setting the priority to namespace.length, we ensure that if one namespace is a prefix of another namespace + // then newly created indices will use the matching template with the *longest* namespace + priority: namespace.length, }; }; diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/data_stream_adapter.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/data_stream_adapter.ts index a4805cd95c5ff..5293cc73c1100 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/data_stream_adapter.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/data_stream_adapter.ts @@ -208,11 +208,9 @@ async function createAliasStream(opts: CreateConcreteWriteIndexOpts): Promise esClient.indices.create({ index: indexPatterns.name, - body: { - aliases: { - [indexPatterns.alias]: { - is_write_index: true, - }, + aliases: { + [indexPatterns.alias]: { + is_write_index: true, }, }, }), diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.test.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.test.ts index 003673f9fdb92..5c911ed35a2e7 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.test.ts @@ -59,42 +59,45 @@ describe('setAlertsToUntracked()', () => { Array [ Object { "allow_no_indices": true, - "body": Object { - "conflicts": "proceed", - "query": Object { - "bool": Object { - "must": Array [ - Object { - "term": Object { - "kibana.alert.status": Object { - "value": "active", - }, + "conflicts": "proceed", + "index": Array [ + "test-index", + ], + "query": Object { + "bool": Object { + "must": Array [ + Object { + "term": Object { + "kibana.alert.status": Object { + "value": "active", }, }, - Object { - "bool": Object { - "should": Array [ - Object { - "term": Object { - "kibana.alert.rule.uuid": Object { - "value": "test-rule", - }, + }, + Object { + "bool": Object { + "should": Array [ + Object { + "term": Object { + "kibana.alert.rule.uuid": Object { + "value": "test-rule", }, }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "should": Array [], - }, + }, + Object { + "bool": Object { + "should": Array [], }, - ], - }, + }, + ], }, - "script": Object { - "lang": "painless", - "source": " + }, + "refresh": true, + "script": Object { + "lang": "painless", + "source": " if (!ctx._source.containsKey('kibana.alert.status') || ctx._source['kibana.alert.status'].empty) { ctx._source.kibana.alert.status = 'untracked'; ctx._source.kibana.alert.end = '2023-03-28T22:27:28.159Z'; @@ -104,12 +107,7 @@ describe('setAlertsToUntracked()', () => { ctx._source['kibana.alert.end'] = '2023-03-28T22:27:28.159Z'; ctx._source['kibana.alert.time_range'].lte = '2023-03-28T22:27:28.159Z'; }", - }, }, - "index": Array [ - "test-index", - ], - "refresh": true, }, ] `); @@ -128,42 +126,45 @@ describe('setAlertsToUntracked()', () => { Array [ Object { "allow_no_indices": true, - "body": Object { - "conflicts": "proceed", - "query": Object { - "bool": Object { - "must": Array [ - Object { - "term": Object { - "kibana.alert.status": Object { - "value": "active", - }, + "conflicts": "proceed", + "index": Array [ + "test-index", + ], + "query": Object { + "bool": Object { + "must": Array [ + Object { + "term": Object { + "kibana.alert.status": Object { + "value": "active", }, }, - Object { - "bool": Object { - "should": Array [], - }, + }, + Object { + "bool": Object { + "should": Array [], }, - Object { - "bool": Object { - "should": Array [ - Object { - "term": Object { - "kibana.alert.uuid": Object { - "value": "test-alert", - }, + }, + Object { + "bool": Object { + "should": Array [ + Object { + "term": Object { + "kibana.alert.uuid": Object { + "value": "test-alert", }, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "script": Object { - "lang": "painless", - "source": " + }, + "refresh": true, + "script": Object { + "lang": "painless", + "source": " if (!ctx._source.containsKey('kibana.alert.status') || ctx._source['kibana.alert.status'].empty) { ctx._source.kibana.alert.status = 'untracked'; ctx._source.kibana.alert.end = '2023-03-28T22:27:28.159Z'; @@ -173,12 +174,7 @@ describe('setAlertsToUntracked()', () => { ctx._source['kibana.alert.end'] = '2023-03-28T22:27:28.159Z'; ctx._source['kibana.alert.time_range'].lte = '2023-03-28T22:27:28.159Z'; }", - }, }, - "index": Array [ - "test-index", - ], - "refresh": true, }, ] `); @@ -457,63 +453,59 @@ describe('setAlertsToUntracked()', () => { expect(clusterClient.updateByQuery).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: { - bool: { - must: [ - { - term: { - 'kibana.alert.status': { - value: 'active', // This has to be active - }, + query: { + bool: { + must: [ + { + term: { + 'kibana.alert.status': { + value: 'active', // This has to be active }, }, - ], - filter: [ - { - bool: { - must: { - term: { - 'kibana.alert.rule.name': 'test', - }, + }, + ], + filter: [ + { + bool: { + must: { + term: { + 'kibana.alert.rule.name': 'test', }, }, }, - ], - }, + }, + ], }, - }), + }, }) ); expect(clusterClient.search).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: { - bool: { - must: [ - { - term: { - 'kibana.alert.status': { - value: 'untracked', // This has to be untracked - }, + query: { + bool: { + must: [ + { + term: { + 'kibana.alert.status': { + value: 'untracked', // This has to be untracked }, }, - ], - filter: [ - { - bool: { - must: { - term: { - 'kibana.alert.rule.name': 'test', - }, + }, + ], + filter: [ + { + bool: { + must: { + term: { + 'kibana.alert.rule.name': 'test', }, }, }, - ], - }, + }, + ], }, - }), + }, }) ); @@ -596,32 +588,30 @@ describe('setAlertsToUntracked()', () => { expect(clusterClient.updateByQuery).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: { - bool: { - must: [ - { - term: { - 'kibana.alert.status': { - value: 'active', // This has to be active - }, + query: { + bool: { + must: [ + { + term: { + 'kibana.alert.status': { + value: 'active', // This has to be active }, }, - ], - filter: [ - { - bool: { - must: { - term: { - 'kibana.alert.rule.name': 'test', - }, + }, + ], + filter: [ + { + bool: { + must: { + term: { + 'kibana.alert.rule.name': 'test', }, }, }, - ], - }, + }, + ], }, - }), + }, }) ); diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.ts index 89c8d671de6a0..6389f4e6639db 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_service/lib/set_alerts_to_untracked.ts @@ -20,7 +20,7 @@ import { ALERT_UUID, AlertStatus, } from '@kbn/rule-data-utils'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { RulesClientContext } from '../../rules_client'; import { AlertingAuthorizationEntity } from '../../authorization/types'; @@ -125,14 +125,12 @@ const ensureAuthorizedToUntrack = async (params: SetAlertsToUntrackedParamsWithD const response = await esClient.search({ index: indices, allow_no_indices: true, - body: { - size: 0, - query: getUntrackQuery(params, ALERT_STATUS_ACTIVE), - aggs: { - ruleTypeIds: { - terms: { field: ALERT_RULE_TYPE_ID }, - aggs: { consumers: { terms: { field: ALERT_RULE_CONSUMER } } }, - }, + size: 0, + query: getUntrackQuery(params, ALERT_STATUS_ACTIVE), + aggs: { + ruleTypeIds: { + terms: { field: ALERT_RULE_TYPE_ID }, + aggs: { consumers: { terms: { field: ALERT_RULE_CONSUMER } } }, }, }, }); @@ -218,14 +216,12 @@ export async function setAlertsToUntracked( const response = await esClient.updateByQuery({ index: indices, allow_no_indices: true, - body: { - conflicts: 'proceed', - script: { - source: getUntrackUpdatePainlessScript(new Date()), - lang: 'painless', - }, - query: getUntrackQuery(params, ALERT_STATUS_ACTIVE), + conflicts: 'proceed', + script: { + source: getUntrackUpdatePainlessScript(new Date()), + lang: 'painless', }, + query: getUntrackQuery(params, ALERT_STATUS_ACTIVE), refresh: true, }); @@ -259,11 +255,9 @@ export async function setAlertsToUntracked( const searchResponse = await esClient.search({ index: indices, allow_no_indices: true, - body: { - _source: [ALERT_RULE_UUID, ALERT_UUID], - size: total, - query: getUntrackQuery(params, ALERT_STATUS_UNTRACKED), - }, + _source: [ALERT_RULE_UUID, ALERT_UUID], + size: total, + query: getUntrackQuery(params, ALERT_STATUS_UNTRACKED), }); return searchResponse.hits.hits.map((hit) => hit._source) as UntrackedAlertsResult; diff --git a/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/types/index.ts b/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/types/index.ts index e146928efcfff..804ed47227e99 100644 --- a/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/types/index.ts +++ b/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/types/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import { TypeOf } from '@kbn/config-schema'; import { KueryNode } from '@kbn/es-query'; import { aggregateOptionsSchema } from '../schemas'; diff --git a/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.ts b/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.ts index 6b61d7aa5c324..df35050455a82 100644 --- a/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.ts +++ b/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.ts @@ -6,7 +6,7 @@ */ import Boom from '@hapi/boom'; -import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; const ALLOW_FIELDS = [ 'alert.attributes.executionStatus.status', diff --git a/x-pack/platform/plugins/shared/alerting/server/authorization/alerting_authorization_kuery.ts b/x-pack/platform/plugins/shared/alerting/server/authorization/alerting_authorization_kuery.ts index 666059c7a7b47..165cdcb2f819d 100644 --- a/x-pack/platform/plugins/shared/alerting/server/authorization/alerting_authorization_kuery.ts +++ b/x-pack/platform/plugins/shared/alerting/server/authorization/alerting_authorization_kuery.ts @@ -8,7 +8,7 @@ import { remove } from 'lodash'; import { EsQueryConfig, nodeBuilder, toElasticsearchQuery, KueryNode } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { AuthorizedRuleTypes } from './alerting_authorization'; export enum AlertingAuthorizationFilterType { diff --git a/x-pack/platform/plugins/shared/alerting/server/invalidate_pending_api_keys/task.ts b/x-pack/platform/plugins/shared/alerting/server/invalidate_pending_api_keys/task.ts index 18364299b99a6..b2e992623a643 100644 --- a/x-pack/platform/plugins/shared/alerting/server/invalidate_pending_api_keys/task.ts +++ b/x-pack/platform/plugins/shared/alerting/server/invalidate_pending_api_keys/task.ts @@ -21,7 +21,7 @@ import { import { AggregationsStringTermsBucketKeys, AggregationsTermsAggregateBase, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from '@kbn/actions-plugin/server/constants/saved_objects'; import { InvalidateAPIKeyResult } from '../rules_client'; import { AlertingConfig } from '../config'; diff --git a/x-pack/platform/plugins/shared/alerting/server/lib/convert_es_sort_to_event_log_sort.ts b/x-pack/platform/plugins/shared/alerting/server/lib/convert_es_sort_to_event_log_sort.ts index 9adb2d0a21e69..b625791031d89 100644 --- a/x-pack/platform/plugins/shared/alerting/server/lib/convert_es_sort_to_event_log_sort.ts +++ b/x-pack/platform/plugins/shared/alerting/server/lib/convert_es_sort_to_event_log_sort.ts @@ -5,11 +5,7 @@ * 2.0. */ -import type { - Sort, - FieldSort, - SortCombinations, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { Sort, FieldSort, SortCombinations } from '@elastic/elasticsearch/lib/api/types'; const getFormattedSort = (sort: SortCombinations) => { if (typeof sort === 'string') { diff --git a/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.test.ts b/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.test.ts index 88263ff495b9a..a7d0ec20cda8c 100644 --- a/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression } from '@kbn/es-query'; import { getNumExecutions, diff --git a/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.ts b/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.ts index 30f495efbf087..511360475929c 100644 --- a/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; import { KueryNode } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import Boom from '@hapi/boom'; import { flatMap, get, isEmpty } from 'lodash'; import { AggregateEventsBySavedObjectResult } from '@kbn/event-log-plugin/server'; diff --git a/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.test.ts b/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.test.ts index e287712104949..60c4de3859fcc 100644 --- a/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.test.ts @@ -11,7 +11,7 @@ import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { createWrappedScopedClusterClientFactory } from './wrap_scoped_cluster_client'; const esQuery = { - body: { query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } } }, + query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } }, }; const eqlQuery = { index: 'foo', @@ -73,7 +73,7 @@ describe('wrapScopedClusterClient', () => { expect(scopedClusterClient.asInternalUser.search).not.toHaveBeenCalled(); expect(scopedClusterClient.asCurrentUser.search).not.toHaveBeenCalled(); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {} and 5000ms requestTimeout` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {} and 5000ms requestTimeout` ); expect(loggingSystemMock.collect(logger).trace[0][0]).toEqual( `result of executing query for rule .test-rule-type:abcdefg in space my-space: {\"body\":{},\"statusCode\":200,\"headers\":{\"x-elastic-product\":\"Elasticsearch\"},\"warnings\":[],\"meta\":{}}` @@ -102,7 +102,7 @@ describe('wrapScopedClusterClient', () => { expect(scopedClusterClient.asInternalUser.search).not.toHaveBeenCalled(); expect(scopedClusterClient.asCurrentUser.search).not.toHaveBeenCalled(); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {} and 5000ms requestTimeout` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {} and 5000ms requestTimeout` ); expect(loggingSystemMock.collect(logger).trace[0][0]).toEqual( `result of executing query for rule .test-rule-type:abcdefg in space my-space: {\"body\":{},\"statusCode\":200,\"headers\":{\"x-elastic-product\":\"Elasticsearch\"},\"warnings\":[],\"meta\":{}}` @@ -136,7 +136,7 @@ describe('wrapScopedClusterClient', () => { expect(scopedClusterClient.asCurrentUser.search).not.toHaveBeenCalled(); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {\"ignore\":[404],\"requestTimeout\":10000} and 5000ms requestTimeout` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {\"ignore\":[404],\"requestTimeout\":10000} and 5000ms requestTimeout` ); expect(loggingSystemMock.collect(logger).trace[0][0]).toEqual( `result of executing query for rule .test-rule-type:abcdefg in space my-space: {\"body\":{},\"statusCode\":200,\"headers\":{\"x-elastic-product\":\"Elasticsearch\"},\"warnings\":[],\"meta\":{}}` @@ -161,11 +161,11 @@ describe('wrapScopedClusterClient', () => { ).rejects.toThrowErrorMatchingInlineSnapshot(`"something went wrong!"`); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {}` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {}` ); expect(logger.trace).not.toHaveBeenCalled(); expect(logger.warn).toHaveBeenCalledWith( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {}` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {}` ); }); @@ -195,7 +195,7 @@ describe('wrapScopedClusterClient', () => { expect(stats.esSearchDurationMs).toEqual(0); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {}` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {}` ); expect(loggingSystemMock.collect(logger).trace[0][0]).toEqual( `result of executing query for rule .test-rule-type:abcdefg in space my-space: {}` @@ -230,7 +230,7 @@ describe('wrapScopedClusterClient', () => { expect(stats.esSearchDurationMs).toEqual(999); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {}` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {}` ); expect(loggingSystemMock.collect(logger).trace[0][0]).toEqual( `result of executing query for rule .test-rule-type:abcdefg in space my-space: {\"took\":333}` @@ -258,7 +258,7 @@ describe('wrapScopedClusterClient', () => { ); expect(loggingSystemMock.collect(logger).debug[0][0]).toEqual( - `executing query for rule .test-rule-type:abcdefg in space my-space - {\"body\":{\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}}} - with options {}` + `executing query for rule .test-rule-type:abcdefg in space my-space - {\"query\":{\"bool\":{\"filter\":{\"range\":{\"@timestamp\":{\"gte\":0}}}}}} - with options {}` ); expect(logger.trace).not.toHaveBeenCalled(); expect(logger.warn).not.toHaveBeenCalled(); diff --git a/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.ts b/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.ts index 3bf87b3653c5a..002895843bf48 100644 --- a/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.ts +++ b/x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.ts @@ -23,7 +23,7 @@ import type { SearchRequest as SearchRequestWithBody, AggregationsAggregate, EqlSearchRequest as EqlSearchRequestWithBody, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { IScopedClusterClient, ElasticsearchClient, Logger } from '@kbn/core/server'; import { SearchMetrics, RuleInfo } from './types'; diff --git a/x-pack/platform/plugins/shared/alerting/server/monitoring/register_cluster_collector.ts b/x-pack/platform/plugins/shared/alerting/server/monitoring/register_cluster_collector.ts index 11832a5e5d00d..93fe8a44f1367 100644 --- a/x-pack/platform/plugins/shared/alerting/server/monitoring/register_cluster_collector.ts +++ b/x-pack/platform/plugins/shared/alerting/server/monitoring/register_cluster_collector.ts @@ -7,7 +7,7 @@ import type { AggregationsKeyedPercentiles, AggregationsPercentilesAggregateBase, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { MonitoringCollectionSetup } from '@kbn/monitoring-collection-plugin/server'; import { aggregateTaskOverduePercentilesForType } from '@kbn/task-manager-plugin/server'; import { CoreSetup } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_alerts.ts b/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_alerts.ts index 5ad7e7a8ac437..d6ef380bfe186 100644 --- a/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_alerts.ts +++ b/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_alerts.ts @@ -12,7 +12,7 @@ import { getRequestAbortedSignal } from '@kbn/data-plugin/server'; import { termsAggSuggestions } from '@kbn/unified-search-plugin/server/autocomplete/terms_agg'; import type { ConfigSchema } from '@kbn/unified-search-plugin/server/config'; import { getKbnServerError, reportServerError } from '@kbn/kibana-utils-plugin/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ALERT_RULE_CONSUMER, ALERT_RULE_TYPE_ID, SPACE_IDS } from '@kbn/rule-data-utils'; import { verifyAccessAndContext } from '../lib'; diff --git a/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_rules.ts b/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_rules.ts index 1f33cba025396..8457a5d5bd86f 100644 --- a/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_rules.ts +++ b/x-pack/platform/plugins/shared/alerting/server/routes/suggestions/values_suggestion_rules.ts @@ -14,7 +14,7 @@ import type { ConfigSchema } from '@kbn/unified-search-plugin/server/config'; import { UsageCounter } from '@kbn/usage-collection-plugin/server'; import { getKbnServerError, reportServerError } from '@kbn/kibana-utils-plugin/server'; import { ALERTING_CASES_SAVED_OBJECT_INDEX } from '@kbn/core-saved-objects-server/src/saved_objects_index_pattern'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { verifyAccessAndContext } from '../lib'; import { ILicenseState } from '../../lib'; diff --git a/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_action_error_log.ts b/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_action_error_log.ts index 4d71af6573b57..d2b8797ed1480 100644 --- a/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_action_error_log.ts +++ b/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_action_error_log.ts @@ -6,7 +6,7 @@ */ import { KueryNode } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SanitizedRuleWithLegacyId } from '../../types'; import { convertEsSortToEventLogSort } from '../../lib'; import { diff --git a/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_execution_log.ts b/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_execution_log.ts index 95d41a02a685b..c047a8a525c81 100644 --- a/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_execution_log.ts +++ b/x-pack/platform/plugins/shared/alerting/server/rules_client/methods/get_execution_log.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { KueryNode } from '@kbn/es-query'; import { SanitizedRuleWithLegacyId } from '../../types'; import { diff --git a/x-pack/platform/plugins/shared/alerting/server/rules_client/tests/get_execution_log.test.ts b/x-pack/platform/plugins/shared/alerting/server/rules_client/tests/get_execution_log.test.ts index 3a3f801dd9085..b5c1f6aa7b365 100644 --- a/x-pack/platform/plugins/shared/alerting/server/rules_client/tests/get_execution_log.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/rules_client/tests/get_execution_log.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RulesClient, ConstructorOptions } from '../rules_client'; import { savedObjectsClientMock, diff --git a/x-pack/platform/plugins/shared/alerting/server/saved_objects/partially_update_rule.test.ts b/x-pack/platform/plugins/shared/alerting/server/saved_objects/partially_update_rule.test.ts index 1bbf7aa448fd4..444fa322012b1 100644 --- a/x-pack/platform/plugins/shared/alerting/server/saved_objects/partially_update_rule.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/saved_objects/partially_update_rule.test.ts @@ -18,7 +18,7 @@ import { import { elasticsearchServiceMock, savedObjectsClientMock } from '@kbn/core/server/mocks'; import { RULE_SAVED_OBJECT_TYPE } from '.'; import { ALERTING_CASES_SAVED_OBJECT_INDEX } from '@kbn/core-saved-objects-server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { RuleExecutionStatuses } from '@kbn/alerting-types'; const MockSavedObjectsClientContract = savedObjectsClientMock.create(); diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.test.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.test.ts index 8ffd71b2ae829..36489e7b73747 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.test.ts @@ -45,7 +45,7 @@ describe('kibana index telemetry', () => { const debugLogs = loggingSystemMock.collect(logger).debug; expect(debugLogs).toHaveLength(2); expect(debugLogs[0][0]).toEqual( - `query for getTotalAlertsCountAggregations - {\"index\":\".alerts-*\",\"size\":0,\"body\":{\"query\":{\"match_all\":{}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"kibana.alert.rule.rule_type_id\",\"size\":33}}}}}` + `query for getTotalAlertsCountAggregations - {\"index\":\".alerts-*\",\"size\":0,\"query\":{\"match_all\":{}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"kibana.alert.rule.rule_type_id\",\"size\":33}}}}` ); expect(debugLogs[1][0]).toEqual( `results for getTotalAlertsCountAggregations query - {\"took\":4,\"timed_out\":false,\"_shards\":{\"total\":1,\"successful\":1,\"skipped\":0,\"failed\":0},\"hits\":{\"total\":{\"value\":6,\"relation\":\"eq\"},\"max_score\":null,\"hits\":[]},\"aggregations\":{\"by_rule_type_id\":{\"doc_count_error_upper_bound\":0,\"sum_other_doc_count\":0,\"buckets\":[{\"key\":\".index-threshold\",\"doc_count\":1},{\"key\":\"logs.alert.document.count\",\"doc_count\":2},{\"key\":\"document.test.\",\"doc_count\":3}]}}}` @@ -93,7 +93,7 @@ describe('kibana index telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(1); expect(loggerCalls.debug[0][0]).toEqual( - `query for getTotalAlertsCountAggregations - {\"index\":\".alerts-*\",\"size\":0,\"body\":{\"query\":{\"match_all\":{}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"kibana.alert.rule.rule_type_id\",\"size\":33}}}}}` + `query for getTotalAlertsCountAggregations - {\"index\":\".alerts-*\",\"size\":0,\"query\":{\"match_all\":{}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"kibana.alert.rule.rule_type_id\",\"size\":33}}}}` ); expect(loggerCalls.warn).toHaveLength(1); expect(loggerCalls.warn[0][0]).toEqual( @@ -143,7 +143,7 @@ describe('kibana index telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(2); expect(loggerCalls.debug[0][0]).toEqual( - `query for getTotalAlertsCountAggregations - {\"index\":\".alerts-*\",\"size\":0,\"body\":{\"query\":{\"match_all\":{}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"kibana.alert.rule.rule_type_id\",\"size\":33}}}}}` + `query for getTotalAlertsCountAggregations - {\"index\":\".alerts-*\",\"size\":0,\"query\":{\"match_all\":{}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"kibana.alert.rule.rule_type_id\",\"size\":33}}}}` ); expect(loggerCalls.debug[1][0]).toMatchInlineSnapshot(` "Error executing alerting telemetry task: getTotalAlertsCountAggregations - ResponseError: search_phase_execution_exception diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.ts index 50acd17a9f9dd..494bcf1d6abc1 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_alerts.ts @@ -8,7 +8,7 @@ import type { AggregationsTermsAggregateBase, AggregationsStringTermsBucketKeys, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, Logger } from '@kbn/core/server'; import { NUM_ALERTING_RULE_TYPES } from '../alerting_usage_collector'; @@ -39,16 +39,14 @@ export async function getTotalAlertsCountAggregations({ const query = { index: AAD_INDEX_PATTERN, size: 0, - body: { - query: { - match_all: {}, - }, - aggs: { - by_rule_type_id: { - terms: { - field: 'kibana.alert.rule.rule_type_id', - size: NUM_ALERTING_RULE_TYPES, - }, + query: { + match_all: {}, + }, + aggs: { + by_rule_type_id: { + terms: { + field: 'kibana.alert.rule.rule_type_id', + size: NUM_ALERTING_RULE_TYPES, }, }, }, diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.test.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.test.ts index 1c8802fdb1726..4c445cf595891 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.test.ts @@ -1468,7 +1468,7 @@ describe('event log telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(2); expect(loggerCalls.debug[0][0]).toEqual( - `query for getExecutionsPerDayCount - {\"index\":\"test\",\"size\":0,\"body\":{\"query\":{\"bool\":{\"filter\":{\"bool\":{\"must\":[{\"term\":{\"event.action\":\"execute\"}},{\"term\":{\"event.provider\":\"alerting\"}},{\"range\":{\"@timestamp\":{\"gte\":\"now-1d\"}}}]}}}},\"aggs\":{\"avg_execution_time\":{\"avg\":{\"field\":\"event.duration\"}},\"avg_es_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.es_search_duration_ms\"}},\"avg_total_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.total_search_duration_ms\"}},\"percentile_scheduled_actions\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.number_of_generated_actions\",\"percents\":[50,90,99]}},\"percentile_alerts\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.alert_counts.active\",\"percents\":[50,90,99]}},\"execution_failures\":{\"filter\":{\"term\":{\"event.outcome\":\"failure\"}},\"aggs\":{\"by_reason\":{\"terms\":{\"field\":\"event.reason\",\"size\":5}}}},\"by_rule_type_id\":{\"terms\":{\"field\":\"rule.category\",\"size\":33},\"aggs\":{\"avg_execution_time\":{\"avg\":{\"field\":\"event.duration\"}},\"avg_es_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.es_search_duration_ms\"}},\"avg_total_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.total_search_duration_ms\"}},\"percentile_scheduled_actions\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.number_of_generated_actions\",\"percents\":[50,90,99]}},\"percentile_alerts\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.alert_counts.active\",\"percents\":[50,90,99]}},\"execution_failures\":{\"filter\":{\"term\":{\"event.outcome\":\"failure\"}},\"aggs\":{\"by_reason\":{\"terms\":{\"field\":\"event.reason\",\"size\":5}}}}}},\"by_execution_status\":{\"terms\":{\"field\":\"event.outcome\"}}}}}` + `query for getExecutionsPerDayCount - {\"index\":\"test\",\"size\":0,\"query\":{\"bool\":{\"filter\":{\"bool\":{\"must\":[{\"term\":{\"event.action\":\"execute\"}},{\"term\":{\"event.provider\":\"alerting\"}},{\"range\":{\"@timestamp\":{\"gte\":\"now-1d\"}}}]}}}},\"aggs\":{\"avg_execution_time\":{\"avg\":{\"field\":\"event.duration\"}},\"avg_es_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.es_search_duration_ms\"}},\"avg_total_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.total_search_duration_ms\"}},\"percentile_scheduled_actions\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.number_of_generated_actions\",\"percents\":[50,90,99]}},\"percentile_alerts\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.alert_counts.active\",\"percents\":[50,90,99]}},\"execution_failures\":{\"filter\":{\"term\":{\"event.outcome\":\"failure\"}},\"aggs\":{\"by_reason\":{\"terms\":{\"field\":\"event.reason\",\"size\":5}}}},\"by_rule_type_id\":{\"terms\":{\"field\":\"rule.category\",\"size\":33},\"aggs\":{\"avg_execution_time\":{\"avg\":{\"field\":\"event.duration\"}},\"avg_es_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.es_search_duration_ms\"}},\"avg_total_search_duration\":{\"avg\":{\"field\":\"kibana.alert.rule.execution.metrics.total_search_duration_ms\"}},\"percentile_scheduled_actions\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.number_of_generated_actions\",\"percents\":[50,90,99]}},\"percentile_alerts\":{\"percentiles\":{\"field\":\"kibana.alert.rule.execution.metrics.alert_counts.active\",\"percents\":[50,90,99]}},\"execution_failures\":{\"filter\":{\"term\":{\"event.outcome\":\"failure\"}},\"aggs\":{\"by_reason\":{\"terms\":{\"field\":\"event.reason\",\"size\":5}}}}}},\"by_execution_status\":{\"terms\":{\"field\":\"event.outcome\"}}}}` ); expect(loggerCalls.debug[1][0]).toMatchInlineSnapshot(` "Error executing alerting telemetry task: getExecutionsPerDayCount - ResponseError: search_phase_execution_exception @@ -1604,7 +1604,7 @@ describe('event log telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(2); expect(loggerCalls.debug[0][0]).toEqual( - `query for getExecutionTimeoutsPerDayCount - {\"index\":\"test\",\"size\":0,\"body\":{\"query\":{\"bool\":{\"filter\":{\"bool\":{\"must\":[{\"term\":{\"event.action\":\"execute-timeout\"}},{\"term\":{\"event.provider\":\"alerting\"}},{\"range\":{\"@timestamp\":{\"gte\":\"now-1d\"}}}]}}}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"rule.category\",\"size\":33}}}}}` + `query for getExecutionTimeoutsPerDayCount - {\"index\":\"test\",\"size\":0,\"query\":{\"bool\":{\"filter\":{\"bool\":{\"must\":[{\"term\":{\"event.action\":\"execute-timeout\"}},{\"term\":{\"event.provider\":\"alerting\"}},{\"range\":{\"@timestamp\":{\"gte\":\"now-1d\"}}}]}}}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"rule.category\",\"size\":33}}}}` ); expect(loggerCalls.debug[1][0]).toMatchInlineSnapshot(` "Error executing alerting telemetry task: getExecutionsTimeoutsPerDayCount - ResponseError: search_phase_execution_exception diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.ts index 70d8c5d7cb196..7862ee91c8f72 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.ts @@ -14,7 +14,7 @@ import type { AggregationsTermsAggregateBase, AggregationsStringTermsBucketKeys, AggregationsBuckets, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, Logger } from '@kbn/core/server'; import { NUM_ALERTING_RULE_TYPES, @@ -137,21 +137,19 @@ export async function getExecutionsPerDayCount({ const query = { index: eventLogIndex, size: 0, - body: { - query: getProviderAndActionFilterForTimeRange('execute'), - aggs: { - ...eventLogAggs, - by_rule_type_id: { - terms: { - field: 'rule.category', - size: NUM_ALERTING_RULE_TYPES, - }, - aggs: eventLogAggs, + query: getProviderAndActionFilterForTimeRange('execute'), + aggs: { + ...eventLogAggs, + by_rule_type_id: { + terms: { + field: 'rule.category', + size: NUM_ALERTING_RULE_TYPES, }, - by_execution_status: { - terms: { - field: 'event.outcome', - }, + aggs: eventLogAggs, + }, + by_execution_status: { + terms: { + field: 'event.outcome', }, }, }, @@ -224,14 +222,12 @@ export async function getExecutionTimeoutsPerDayCount({ const query = { index: eventLogIndex, size: 0, - body: { - query: getProviderAndActionFilterForTimeRange('execute-timeout'), - aggs: { - by_rule_type_id: { - terms: { - field: 'rule.category', - size: NUM_ALERTING_RULE_TYPES, - }, + query: getProviderAndActionFilterForTimeRange('execute-timeout'), + aggs: { + by_rule_type_id: { + terms: { + field: 'rule.category', + size: NUM_ALERTING_RULE_TYPES, }, }, }, diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.test.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.test.ts index 3173f17cd5288..5e53b7e83aa0a 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.test.ts @@ -401,7 +401,7 @@ describe('kibana index telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(2); expect(loggerCalls.debug[0][0]).toEqual( - `query for getTotalCountAggregations - {\"index\":\"test\",\"size\":0,\"body\":{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"type\":\"alert\"}}]}},\"runtime_mappings\":{\"rule_action_count\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def alert = params._source['alert'];\\n if (alert != null) {\\n def actions = alert.actions;\\n if (actions != null) {\\n emit(actions.length);\\n } else {\\n emit(0);\\n }\\n }\"}},\"rule_schedule_interval\":{\"type\":\"long\",\"script\":{\"source\":\"\\n int parsed = 0;\\n if (doc['alert.schedule.interval'].size() > 0) {\\n def interval = doc['alert.schedule.interval'].value;\\n\\n if (interval.length() > 1) {\\n // get last char\\n String timeChar = interval.substring(interval.length() - 1);\\n // remove last char\\n interval = interval.substring(0, interval.length() - 1);\\n\\n if (interval.chars().allMatch(Character::isDigit)) {\\n // using of regex is not allowed in painless language\\n parsed = Integer.parseInt(interval);\\n\\n if (timeChar.equals(\\\"s\\\")) {\\n parsed = parsed;\\n } else if (timeChar.equals(\\\"m\\\")) {\\n parsed = parsed * 60;\\n } else if (timeChar.equals(\\\"h\\\")) {\\n parsed = parsed * 60 * 60;\\n } else if (timeChar.equals(\\\"d\\\")) {\\n parsed = parsed * 24 * 60 * 60;\\n }\\n emit(parsed);\\n }\\n }\\n }\\n emit(parsed);\\n \"}},\"rule_throttle_interval\":{\"type\":\"long\",\"script\":{\"source\":\"\\n int parsed = 0;\\n if (doc['alert.throttle'].size() > 0) {\\n def throttle = doc['alert.throttle'].value;\\n\\n if (throttle.length() > 1) {\\n // get last char\\n String timeChar = throttle.substring(throttle.length() - 1);\\n // remove last char\\n throttle = throttle.substring(0, throttle.length() - 1);\\n\\n if (throttle.chars().allMatch(Character::isDigit)) {\\n // using of regex is not allowed in painless language\\n parsed = Integer.parseInt(throttle);\\n\\n if (timeChar.equals(\\\"s\\\")) {\\n parsed = parsed;\\n } else if (timeChar.equals(\\\"m\\\")) {\\n parsed = parsed * 60;\\n } else if (timeChar.equals(\\\"h\\\")) {\\n parsed = parsed * 60 * 60;\\n } else if (timeChar.equals(\\\"d\\\")) {\\n parsed = parsed * 24 * 60 * 60;\\n }\\n emit(parsed);\\n }\\n }\\n }\\n emit(parsed);\\n \"}},\"rule_with_tags\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def rule = params._source['alert'];\\n if (rule != null && rule.tags != null) {\\n if (rule.tags.size() > 0) {\\n emit(1);\\n } else {\\n emit(0);\\n }\\n }\"}},\"rule_snoozed\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def rule = params._source['alert'];\\n if (rule != null && rule.snoozeSchedule != null) {\\n if (rule.snoozeSchedule.size() > 0) {\\n emit(1);\\n } else {\\n emit(0);\\n }\\n }\"}},\"rule_muted\":{\"type\":\"long\",\"script\":{\"source\":\"\\n if (doc['alert.muteAll'].value == true) {\\n emit(1);\\n } else {\\n emit(0);\\n }\"}},\"rule_with_muted_alerts\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def rule = params._source['alert'];\\n if (rule != null && rule.mutedInstanceIds != null) {\\n if (rule.mutedInstanceIds.size() > 0) {\\n emit(1);\\n } else {\\n emit(0);\\n }\\n }\"}}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"alert.alertTypeId\",\"size\":33}},\"max_throttle_time\":{\"max\":{\"field\":\"rule_throttle_interval\"}},\"min_throttle_time\":{\"min\":{\"field\":\"rule_throttle_interval\"}},\"avg_throttle_time\":{\"avg\":{\"field\":\"rule_throttle_interval\"}},\"max_interval_time\":{\"max\":{\"field\":\"rule_schedule_interval\"}},\"min_interval_time\":{\"min\":{\"field\":\"rule_schedule_interval\"}},\"avg_interval_time\":{\"avg\":{\"field\":\"rule_schedule_interval\"}},\"max_actions_count\":{\"max\":{\"field\":\"rule_action_count\"}},\"min_actions_count\":{\"min\":{\"field\":\"rule_action_count\"}},\"avg_actions_count\":{\"avg\":{\"field\":\"rule_action_count\"}},\"by_execution_status\":{\"terms\":{\"field\":\"alert.executionStatus.status\"}},\"by_notify_when\":{\"terms\":{\"field\":\"alert.notifyWhen\"}},\"connector_types_by_consumers\":{\"terms\":{\"field\":\"alert.consumer\"},\"aggs\":{\"actions\":{\"nested\":{\"path\":\"alert.actions\"},\"aggs\":{\"connector_types\":{\"terms\":{\"field\":\"alert.actions.actionTypeId\"}}}}}},\"by_search_type\":{\"terms\":{\"field\":\"alert.params.searchType\"}},\"sum_rules_with_tags\":{\"sum\":{\"field\":\"rule_with_tags\"}},\"sum_rules_snoozed\":{\"sum\":{\"field\":\"rule_snoozed\"}},\"sum_rules_muted\":{\"sum\":{\"field\":\"rule_muted\"}},\"sum_rules_with_muted_alerts\":{\"sum\":{\"field\":\"rule_with_muted_alerts\"}}}}}` + `query for getTotalCountAggregations - {\"index\":\"test\",\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"term\":{\"type\":\"alert\"}}]}},\"runtime_mappings\":{\"rule_action_count\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def alert = params._source['alert'];\\n if (alert != null) {\\n def actions = alert.actions;\\n if (actions != null) {\\n emit(actions.length);\\n } else {\\n emit(0);\\n }\\n }\"}},\"rule_schedule_interval\":{\"type\":\"long\",\"script\":{\"source\":\"\\n int parsed = 0;\\n if (doc['alert.schedule.interval'].size() > 0) {\\n def interval = doc['alert.schedule.interval'].value;\\n\\n if (interval.length() > 1) {\\n // get last char\\n String timeChar = interval.substring(interval.length() - 1);\\n // remove last char\\n interval = interval.substring(0, interval.length() - 1);\\n\\n if (interval.chars().allMatch(Character::isDigit)) {\\n // using of regex is not allowed in painless language\\n parsed = Integer.parseInt(interval);\\n\\n if (timeChar.equals(\\\"s\\\")) {\\n parsed = parsed;\\n } else if (timeChar.equals(\\\"m\\\")) {\\n parsed = parsed * 60;\\n } else if (timeChar.equals(\\\"h\\\")) {\\n parsed = parsed * 60 * 60;\\n } else if (timeChar.equals(\\\"d\\\")) {\\n parsed = parsed * 24 * 60 * 60;\\n }\\n emit(parsed);\\n }\\n }\\n }\\n emit(parsed);\\n \"}},\"rule_throttle_interval\":{\"type\":\"long\",\"script\":{\"source\":\"\\n int parsed = 0;\\n if (doc['alert.throttle'].size() > 0) {\\n def throttle = doc['alert.throttle'].value;\\n\\n if (throttle.length() > 1) {\\n // get last char\\n String timeChar = throttle.substring(throttle.length() - 1);\\n // remove last char\\n throttle = throttle.substring(0, throttle.length() - 1);\\n\\n if (throttle.chars().allMatch(Character::isDigit)) {\\n // using of regex is not allowed in painless language\\n parsed = Integer.parseInt(throttle);\\n\\n if (timeChar.equals(\\\"s\\\")) {\\n parsed = parsed;\\n } else if (timeChar.equals(\\\"m\\\")) {\\n parsed = parsed * 60;\\n } else if (timeChar.equals(\\\"h\\\")) {\\n parsed = parsed * 60 * 60;\\n } else if (timeChar.equals(\\\"d\\\")) {\\n parsed = parsed * 24 * 60 * 60;\\n }\\n emit(parsed);\\n }\\n }\\n }\\n emit(parsed);\\n \"}},\"rule_with_tags\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def rule = params._source['alert'];\\n if (rule != null && rule.tags != null) {\\n if (rule.tags.size() > 0) {\\n emit(1);\\n } else {\\n emit(0);\\n }\\n }\"}},\"rule_snoozed\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def rule = params._source['alert'];\\n if (rule != null && rule.snoozeSchedule != null) {\\n if (rule.snoozeSchedule.size() > 0) {\\n emit(1);\\n } else {\\n emit(0);\\n }\\n }\"}},\"rule_muted\":{\"type\":\"long\",\"script\":{\"source\":\"\\n if (doc['alert.muteAll'].value == true) {\\n emit(1);\\n } else {\\n emit(0);\\n }\"}},\"rule_with_muted_alerts\":{\"type\":\"long\",\"script\":{\"source\":\"\\n def rule = params._source['alert'];\\n if (rule != null && rule.mutedInstanceIds != null) {\\n if (rule.mutedInstanceIds.size() > 0) {\\n emit(1);\\n } else {\\n emit(0);\\n }\\n }\"}}},\"aggs\":{\"by_rule_type_id\":{\"terms\":{\"field\":\"alert.alertTypeId\",\"size\":33}},\"max_throttle_time\":{\"max\":{\"field\":\"rule_throttle_interval\"}},\"min_throttle_time\":{\"min\":{\"field\":\"rule_throttle_interval\"}},\"avg_throttle_time\":{\"avg\":{\"field\":\"rule_throttle_interval\"}},\"max_interval_time\":{\"max\":{\"field\":\"rule_schedule_interval\"}},\"min_interval_time\":{\"min\":{\"field\":\"rule_schedule_interval\"}},\"avg_interval_time\":{\"avg\":{\"field\":\"rule_schedule_interval\"}},\"max_actions_count\":{\"max\":{\"field\":\"rule_action_count\"}},\"min_actions_count\":{\"min\":{\"field\":\"rule_action_count\"}},\"avg_actions_count\":{\"avg\":{\"field\":\"rule_action_count\"}},\"by_execution_status\":{\"terms\":{\"field\":\"alert.executionStatus.status\"}},\"by_notify_when\":{\"terms\":{\"field\":\"alert.notifyWhen\"}},\"connector_types_by_consumers\":{\"terms\":{\"field\":\"alert.consumer\"},\"aggs\":{\"actions\":{\"nested\":{\"path\":\"alert.actions\"},\"aggs\":{\"connector_types\":{\"terms\":{\"field\":\"alert.actions.actionTypeId\"}}}}}},\"by_search_type\":{\"terms\":{\"field\":\"alert.params.searchType\"}},\"sum_rules_with_tags\":{\"sum\":{\"field\":\"rule_with_tags\"}},\"sum_rules_snoozed\":{\"sum\":{\"field\":\"rule_snoozed\"}},\"sum_rules_muted\":{\"sum\":{\"field\":\"rule_muted\"}},\"sum_rules_with_muted_alerts\":{\"sum\":{\"field\":\"rule_with_muted_alerts\"}}}}` ); expect(loggerCalls.debug[1][0]).toMatchInlineSnapshot(` "Error executing alerting telemetry task: getTotalCountAggregations - ResponseError: search_phase_execution_exception @@ -566,7 +566,7 @@ describe('kibana index telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(2); expect(loggerCalls.debug[0][0]).toEqual( - `query for getTotalCountInUse - {\"index\":\"test\",\"size\":0,\"body\":{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"type\":\"alert\"}},{\"term\":{\"alert.enabled\":true}}]}},\"aggs\":{\"namespaces_count\":{\"cardinality\":{\"field\":\"namespaces\"}},\"by_rule_type_id\":{\"terms\":{\"field\":\"alert.alertTypeId\",\"size\":33}},\"by_search_type\":{\"terms\":{\"field\":\"alert.params.searchType\"}}}}}` + `query for getTotalCountInUse - {\"index\":\"test\",\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"term\":{\"type\":\"alert\"}},{\"term\":{\"alert.enabled\":true}}]}},\"aggs\":{\"namespaces_count\":{\"cardinality\":{\"field\":\"namespaces\"}},\"by_rule_type_id\":{\"terms\":{\"field\":\"alert.alertTypeId\",\"size\":33}},\"by_search_type\":{\"terms\":{\"field\":\"alert.params.searchType\"}}}}` ); expect(loggerCalls.debug[1][0]).toMatchInlineSnapshot(` "Error executing alerting telemetry task: getTotalCountInUse - ResponseError: search_phase_execution_exception diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.ts index de9238f2eb904..2f285e17e9cb2 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_kibana.ts @@ -10,7 +10,7 @@ import type { AggregationsCardinalityAggregate, AggregationsTermsAggregateBase, AggregationsStringTermsBucketKeys, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, Logger, ISavedObjectsRepository } from '@kbn/core/server'; import { @@ -84,18 +84,17 @@ export async function getTotalCountAggregations({ const query = { index: alertIndex, size: 0, - body: { - query: { - bool: { - // Aggregate over all rule saved objects - filter: [{ term: { type: 'alert' } }], - }, + query: { + bool: { + // Aggregate over all rule saved objects + filter: [{ term: { type: 'alert' } }], }, - runtime_mappings: { - rule_action_count: { - type: 'long', - script: { - source: ` + }, + runtime_mappings: { + rule_action_count: { + type: 'long' as const, + script: { + source: ` def alert = params._source['alert']; if (alert != null) { def actions = alert.actions; @@ -105,13 +104,13 @@ export async function getTotalCountAggregations({ emit(0); } }`, - }, }, - // Convert schedule interval duration string from rule saved object to interval in seconds - rule_schedule_interval: { - type: 'long', - script: { - source: ` + }, + // Convert schedule interval duration string from rule saved object to interval in seconds + rule_schedule_interval: { + type: 'long' as const, + script: { + source: ` int parsed = 0; if (doc['alert.schedule.interval'].size() > 0) { def interval = doc['alert.schedule.interval'].value; @@ -141,13 +140,13 @@ export async function getTotalCountAggregations({ } emit(parsed); `, - }, }, - // Convert throttle interval duration string from rule saved object to interval in seconds - rule_throttle_interval: { - type: 'long', - script: { - source: ` + }, + // Convert throttle interval duration string from rule saved object to interval in seconds + rule_throttle_interval: { + type: 'long' as const, + script: { + source: ` int parsed = 0; if (doc['alert.throttle'].size() > 0) { def throttle = doc['alert.throttle'].value; @@ -177,12 +176,12 @@ export async function getTotalCountAggregations({ } emit(parsed); `, - }, }, - rule_with_tags: { - type: 'long', - script: { - source: ` + }, + rule_with_tags: { + type: 'long' as const, + script: { + source: ` def rule = params._source['alert']; if (rule != null && rule.tags != null) { if (rule.tags.size() > 0) { @@ -191,12 +190,12 @@ export async function getTotalCountAggregations({ emit(0); } }`, - }, }, - rule_snoozed: { - type: 'long', - script: { - source: ` + }, + rule_snoozed: { + type: 'long' as const, + script: { + source: ` def rule = params._source['alert']; if (rule != null && rule.snoozeSchedule != null) { if (rule.snoozeSchedule.size() > 0) { @@ -205,23 +204,23 @@ export async function getTotalCountAggregations({ emit(0); } }`, - }, }, - rule_muted: { - type: 'long', - script: { - source: ` + }, + rule_muted: { + type: 'long' as const, + script: { + source: ` if (doc['alert.muteAll'].value == true) { emit(1); } else { emit(0); }`, - }, }, - rule_with_muted_alerts: { - type: 'long', - script: { - source: ` + }, + rule_with_muted_alerts: { + type: 'long' as const, + script: { + source: ` def rule = params._source['alert']; if (rule != null && rule.mutedInstanceIds != null) { if (rule.mutedInstanceIds.size() > 0) { @@ -230,64 +229,63 @@ export async function getTotalCountAggregations({ emit(0); } }`, - }, }, }, - aggs: { - by_rule_type_id: { - terms: { - field: 'alert.alertTypeId', - size: NUM_ALERTING_RULE_TYPES, - }, + }, + aggs: { + by_rule_type_id: { + terms: { + field: 'alert.alertTypeId', + size: NUM_ALERTING_RULE_TYPES, }, - max_throttle_time: { max: { field: 'rule_throttle_interval' } }, - min_throttle_time: { min: { field: 'rule_throttle_interval' } }, - avg_throttle_time: { avg: { field: 'rule_throttle_interval' } }, - max_interval_time: { max: { field: 'rule_schedule_interval' } }, - min_interval_time: { min: { field: 'rule_schedule_interval' } }, - avg_interval_time: { avg: { field: 'rule_schedule_interval' } }, - max_actions_count: { max: { field: 'rule_action_count' } }, - min_actions_count: { min: { field: 'rule_action_count' } }, - avg_actions_count: { avg: { field: 'rule_action_count' } }, - by_execution_status: { - terms: { - field: 'alert.executionStatus.status', - }, + }, + max_throttle_time: { max: { field: 'rule_throttle_interval' } }, + min_throttle_time: { min: { field: 'rule_throttle_interval' } }, + avg_throttle_time: { avg: { field: 'rule_throttle_interval' } }, + max_interval_time: { max: { field: 'rule_schedule_interval' } }, + min_interval_time: { min: { field: 'rule_schedule_interval' } }, + avg_interval_time: { avg: { field: 'rule_schedule_interval' } }, + max_actions_count: { max: { field: 'rule_action_count' } }, + min_actions_count: { min: { field: 'rule_action_count' } }, + avg_actions_count: { avg: { field: 'rule_action_count' } }, + by_execution_status: { + terms: { + field: 'alert.executionStatus.status', }, - by_notify_when: { - terms: { - field: 'alert.notifyWhen', - }, + }, + by_notify_when: { + terms: { + field: 'alert.notifyWhen', }, - connector_types_by_consumers: { - terms: { - field: 'alert.consumer', - }, - aggs: { - actions: { - nested: { - path: 'alert.actions', - }, - aggs: { - connector_types: { - terms: { - field: 'alert.actions.actionTypeId', - }, + }, + connector_types_by_consumers: { + terms: { + field: 'alert.consumer', + }, + aggs: { + actions: { + nested: { + path: 'alert.actions', + }, + aggs: { + connector_types: { + terms: { + field: 'alert.actions.actionTypeId', }, }, }, }, }, - by_search_type: { - terms: { - field: 'alert.params.searchType', - }, + }, + by_search_type: { + terms: { + field: 'alert.params.searchType', }, - sum_rules_with_tags: { sum: { field: 'rule_with_tags' } }, - sum_rules_snoozed: { sum: { field: 'rule_snoozed' } }, - sum_rules_muted: { sum: { field: 'rule_muted' } }, - sum_rules_with_muted_alerts: { sum: { field: 'rule_with_muted_alerts' } }, }, + sum_rules_with_tags: { sum: { field: 'rule_with_tags' } }, + sum_rules_snoozed: { sum: { field: 'rule_snoozed' } }, + sum_rules_muted: { sum: { field: 'rule_muted' } }, + sum_rules_with_muted_alerts: { sum: { field: 'rule_with_muted_alerts' } }, }, }; @@ -433,25 +431,23 @@ export async function getTotalCountInUse({ const query = { index: alertIndex, size: 0, - body: { - query: { - bool: { - // Aggregate over only enabled rule saved objects - filter: [{ term: { type: 'alert' } }, { term: { 'alert.enabled': true } }], - }, + query: { + bool: { + // Aggregate over only enabled rule saved objects + filter: [{ term: { type: 'alert' } }, { term: { 'alert.enabled': true } }], }, - aggs: { - namespaces_count: { cardinality: { field: 'namespaces' } }, - by_rule_type_id: { - terms: { - field: 'alert.alertTypeId', - size: NUM_ALERTING_RULE_TYPES, - }, + }, + aggs: { + namespaces_count: { cardinality: { field: 'namespaces' } }, + by_rule_type_id: { + terms: { + field: 'alert.alertTypeId', + size: NUM_ALERTING_RULE_TYPES, }, - by_search_type: { - terms: { - field: 'alert.params.searchType', - }, + }, + by_search_type: { + terms: { + field: 'alert.params.searchType', }, }, }, diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.test.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.test.ts index bc18438a04a56..a084788630d0d 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.test.ts @@ -283,7 +283,7 @@ describe('task manager telemetry', () => { const loggerCalls = loggingSystemMock.collect(logger); expect(loggerCalls.debug).toHaveLength(2); expect(loggerCalls.debug[0][0]).toEqual( - `query for getFailedAndUnrecognizedTasksPerDay - {\"index\":\"test\",\"size\":0,\"body\":{\"query\":{\"bool\":{\"must\":[{\"bool\":{\"should\":[{\"term\":{\"task.status\":\"unrecognized\"}},{\"term\":{\"task.status\":\"failed\"}}]}},{\"wildcard\":{\"task.taskType\":{\"value\":\"alerting:*\"}}},{\"range\":{\"task.runAt\":{\"gte\":\"now-1d\"}}}]}},\"aggs\":{\"by_status\":{\"terms\":{\"field\":\"task.status\",\"size\":10},\"aggs\":{\"by_task_type\":{\"terms\":{\"field\":\"task.taskType\",\"size\":33}}}}}}}` + `query for getFailedAndUnrecognizedTasksPerDay - {\"index\":\"test\",\"size\":0,\"query\":{\"bool\":{\"must\":[{\"bool\":{\"should\":[{\"term\":{\"task.status\":\"unrecognized\"}},{\"term\":{\"task.status\":\"failed\"}}]}},{\"wildcard\":{\"task.taskType\":{\"value\":\"alerting:*\"}}},{\"range\":{\"task.runAt\":{\"gte\":\"now-1d\"}}}]}},\"aggs\":{\"by_status\":{\"terms\":{\"field\":\"task.status\",\"size\":10},\"aggs\":{\"by_task_type\":{\"terms\":{\"field\":\"task.taskType\",\"size\":33}}}}}}` ); expect(loggerCalls.debug[1][0]).toMatchInlineSnapshot(` "Error executing alerting telemetry task: getFailedAndUnrecognizedTasksPerDay - ResponseError: search_phase_execution_exception diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.ts index 9658bbcabf1af..adddb7cd7ee2d 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.ts @@ -10,7 +10,7 @@ import type { AggregationsTermsAggregateBase, AggregationsStringTermsBucketKeys, AggregationsBuckets, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, Logger } from '@kbn/core/server'; import { replaceDotSymbols } from './replace_dots_with_underscores'; import { NUM_ALERTING_RULE_TYPES } from '../alerting_usage_collector'; @@ -43,58 +43,56 @@ export async function getFailedAndUnrecognizedTasksPerDay({ const query = { index: taskManagerIndex, size: 0, - body: { - query: { - bool: { - must: [ - { - bool: { - should: [ - { - term: { - 'task.status': 'unrecognized', - }, + query: { + bool: { + must: [ + { + bool: { + should: [ + { + term: { + 'task.status': 'unrecognized', }, - { - term: { - 'task.status': 'failed', - }, + }, + { + term: { + 'task.status': 'failed', }, - ], - }, - }, - { - wildcard: { - 'task.taskType': { - value: 'alerting:*', }, - }, + ], }, - { - range: { - 'task.runAt': { - gte: 'now-1d', - }, + }, + { + wildcard: { + 'task.taskType': { + value: 'alerting:*', }, }, - ], - }, - }, - aggs: { - by_status: { - terms: { - field: 'task.status', - size: 10, }, - aggs: { - by_task_type: { - terms: { - field: 'task.taskType', - // Use number of alerting rule types because we're filtering by 'alerting:' - size: NUM_ALERTING_RULE_TYPES, + { + range: { + 'task.runAt': { + gte: 'now-1d', }, }, }, + ], + }, + }, + aggs: { + by_status: { + terms: { + field: 'task.status', + size: 10, + }, + aggs: { + by_task_type: { + terms: { + field: 'task.taskType', + // Use number of alerting rule types because we're filtering by 'alerting:' + size: NUM_ALERTING_RULE_TYPES, + }, + }, }, }, }, diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/group_connectors_by_consumers.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/group_connectors_by_consumers.ts index 3c29f31f0eb9f..21c7a9b4737d4 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/group_connectors_by_consumers.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/group_connectors_by_consumers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AggregationsBuckets } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsBuckets } from '@elastic/elasticsearch/lib/api/types'; import { replaceDotSymbols } from './replace_dots_with_underscores'; export interface ConnectorsByConsumersBucket { diff --git a/x-pack/platform/plugins/shared/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts b/x-pack/platform/plugins/shared/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts index f3d3007061365..8af7fc6d5e15b 100644 --- a/x-pack/platform/plugins/shared/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts +++ b/x-pack/platform/plugins/shared/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts @@ -8,7 +8,7 @@ import { AggregationsBuckets, AggregationsStringTermsBucketKeys, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { replaceDotSymbols } from './replace_dots_with_underscores'; export function parseSimpleRuleTypeBucket( diff --git a/x-pack/platform/plugins/shared/cases/public/containers/types.ts b/x-pack/platform/plugins/shared/cases/public/containers/types.ts index d23d18c6e7896..885cd4b577d7b 100644 --- a/x-pack/platform/plugins/shared/cases/public/containers/types.ts +++ b/x-pack/platform/plugins/shared/cases/public/containers/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export * from '../../common/ui'; diff --git a/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts b/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts index b739abd848294..179a9aa25c978 100644 --- a/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts +++ b/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts @@ -7,7 +7,7 @@ import { get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SingleCaseMetricsResponse } from '../../../../../common/types/api'; import type { AggregationBuilder, AggregationResponse } from '../../types'; diff --git a/x-pack/platform/plugins/shared/cases/server/client/metrics/types.ts b/x-pack/platform/plugins/shared/cases/server/client/metrics/types.ts index dd832be3d93f0..e5ac446c95188 100644 --- a/x-pack/platform/plugins/shared/cases/server/client/metrics/types.ts +++ b/x-pack/platform/plugins/shared/cases/server/client/metrics/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { CasesMetricsFeatureField, SingleCaseMetricsFeatureField, diff --git a/x-pack/platform/plugins/shared/cases/server/services/alerts/index.test.ts b/x-pack/platform/plugins/shared/cases/server/services/alerts/index.test.ts index 450efd67c9e12..644695d31589b 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/alerts/index.test.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/alerts/index.test.ts @@ -38,28 +38,26 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "alert-id-1", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'closed' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": ".siem-signals", + "query": Object { + "ids": Object { + "values": Array [ + "alert-id-1", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'closed' + }", + }, }, ] `); @@ -77,29 +75,27 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "id1", - "id2", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'closed' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": "1", + "query": Object { + "ids": Object { + "values": Array [ + "id1", + "id2", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'closed' + }", + }, }, ] `); @@ -114,28 +110,26 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "id1", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'acknowledged'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'acknowledged' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": "1", + "query": Object { + "ids": Object { + "values": Array [ + "id1", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'acknowledged'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'acknowledged' + }", + }, }, ] `); @@ -154,28 +148,26 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "id1", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'closed' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": "1", + "query": Object { + "ids": Object { + "values": Array [ + "id1", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'closed' + }", + }, }, ] `); @@ -184,28 +176,26 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[1]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "id2", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'open'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'open' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": "1", + "query": Object { + "ids": Object { + "values": Array [ + "id2", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'open'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'open' + }", + }, }, ] `); @@ -224,28 +214,26 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "id1", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'closed'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'closed' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": "1", + "query": Object { + "ids": Object { + "values": Array [ + "id1", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'closed'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'closed' + }", + }, }, ] `); @@ -254,28 +242,26 @@ describe('updateAlertsStatus', () => { expect(esClient.updateByQuery.mock.calls[1]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "ids": Object { - "values": Array [ - "id2", - ], - }, - }, - "script": Object { - "lang": "painless", - "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { - ctx._source['kibana.alert.workflow_status'] = 'open'; - ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = 'open' - }", - }, - }, "conflicts": "abort", "ignore_unavailable": true, "index": "2", + "query": Object { + "ids": Object { + "values": Array [ + "id2", + ], + }, + }, + "script": Object { + "lang": "painless", + "source": "if (ctx._source['kibana.alert.workflow_status'] != null) { + ctx._source['kibana.alert.workflow_status'] = 'open'; + ctx._source['kibana.alert.workflow_status_updated_at'] = '2022-02-21T17:35:00.000Z'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = 'open' + }", + }, }, ] `); @@ -318,14 +304,12 @@ describe('updateAlertsStatus', () => { ]); expect(esClient.mget).toHaveBeenCalledWith({ - body: { - docs: [ - { - _id: 'c3869d546717e8c581add9cbf7d24578f34cd3e72cbc8d8b8e9a9330a899f70f', - _index: '.internal.alerts-security.alerts-default-000001', - }, - ], - }, + docs: [ + { + _id: 'c3869d546717e8c581add9cbf7d24578f34cd3e72cbc8d8b8e9a9330a899f70f', + _index: '.internal.alerts-security.alerts-default-000001', + }, + ], }); expect(res).toEqual({ docs }); diff --git a/x-pack/platform/plugins/shared/cases/server/services/alerts/index.ts b/x-pack/platform/plugins/shared/cases/server/services/alerts/index.ts index 94694b7f243b5..23ba5c8333a72 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/alerts/index.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/alerts/index.ts @@ -169,21 +169,19 @@ export class AlertService { this.scopedClusterClient.updateByQuery({ index, conflicts: 'abort', - body: { - script: { - source: `if (ctx._source['${ALERT_WORKFLOW_STATUS}'] != null) { - ctx._source['${ALERT_WORKFLOW_STATUS}'] = '${status}'; - ctx._source['${ALERT_WORKFLOW_STATUS_UPDATED_AT}'] = '${new Date().toISOString()}'; - } - if (ctx._source.signal != null && ctx._source.signal.status != null) { - ctx._source.signal.status = '${status}' - }`, - lang: 'painless', - }, - // the query here will contain all the ids that have the same status for the same index - // being updated - query: { ids: { values: translatedAlerts.map(({ id }) => id) } }, + script: { + source: `if (ctx._source['${ALERT_WORKFLOW_STATUS}'] != null) { + ctx._source['${ALERT_WORKFLOW_STATUS}'] = '${status}'; + ctx._source['${ALERT_WORKFLOW_STATUS_UPDATED_AT}'] = '${new Date().toISOString()}'; + } + if (ctx._source.signal != null && ctx._source.signal.status != null) { + ctx._source.signal.status = '${status}' + }`, + lang: 'painless', }, + // the query here will contain all the ids that have the same status for the same index + // being updated + query: { ids: { values: translatedAlerts.map(({ id }) => id) } }, ignore_unavailable: true, }) ) @@ -205,7 +203,7 @@ export class AlertService { return; } - const results = await this.scopedClusterClient.mget({ body: { docs } }); + const results = await this.scopedClusterClient.mget({ docs }); return results; } catch (error) { diff --git a/x-pack/platform/plugins/shared/cases/server/services/attachments/index.ts b/x-pack/platform/plugins/shared/cases/server/services/attachments/index.ts index 165949b0e37d8..63ddde40d8048 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/attachments/index.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/attachments/index.ts @@ -13,7 +13,7 @@ import type { SavedObjectsUpdateResponse, } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression } from '@kbn/es-query'; import { AttachmentAttributesRt, AttachmentType } from '../../../common/types/domain'; import { decodeOrThrow } from '../../common/runtime_types'; diff --git a/x-pack/platform/plugins/shared/cases/server/services/attachments/operations/get.ts b/x-pack/platform/plugins/shared/cases/server/services/attachments/operations/get.ts index da258afc5eeb9..6ecda8a7dde36 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/attachments/operations/get.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/attachments/operations/get.ts @@ -10,7 +10,7 @@ import type { SavedObjectsBulkResponse, SavedObjectsFindResponse, } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { FILE_SO_TYPE } from '@kbn/files-plugin/common'; import { isSOError } from '../../../common/error'; import { decodeOrThrow } from '../../../common/runtime_types'; diff --git a/x-pack/platform/plugins/shared/cases/server/services/attachments/types.ts b/x-pack/platform/plugins/shared/cases/server/services/attachments/types.ts index c9c5de01e3a4a..2fc303d648d64 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/attachments/types.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/attachments/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Logger, SavedObject, diff --git a/x-pack/platform/plugins/shared/cases/server/services/cases/index.ts b/x-pack/platform/plugins/shared/cases/server/services/cases/index.ts index 034e369b1c700..adf49922d1a18 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/cases/index.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/cases/index.ts @@ -18,7 +18,7 @@ import type { SavedObjectsBulkDeleteOptions, } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { nodeBuilder } from '@kbn/es-query'; import type { Case, CaseStatuses, User } from '../../../common/types/domain'; diff --git a/x-pack/platform/plugins/shared/cases/server/services/user_actions/index.ts b/x-pack/platform/plugins/shared/cases/server/services/user_actions/index.ts index 911f31c5c52f2..0c73e488454da 100644 --- a/x-pack/platform/plugins/shared/cases/server/services/user_actions/index.ts +++ b/x-pack/platform/plugins/shared/cases/server/services/user_actions/index.ts @@ -11,7 +11,7 @@ import type { SavedObjectsRawDoc, } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { KueryNode } from '@kbn/es-query'; import type { CaseUserActionDeprecatedResponse } from '../../../common/types/api'; import { UserActionTypes } from '../../../common/types/domain'; diff --git a/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_dataset_aggregated_paginated_results.ts b/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_dataset_aggregated_paginated_results.ts index 2935e2d24592a..a174b5fad0385 100644 --- a/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_dataset_aggregated_paginated_results.ts +++ b/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_dataset_aggregated_paginated_results.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslBoolQuery } from '@elastic/elasticsearch/lib/api/types'; +import type { QueryDslBoolQuery } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient } from '@kbn/core/server'; import { extractIndexNameFromBackingIndex } from '../../../common/utils'; import { DataStreamDocsStat } from '../../../common/api_types'; diff --git a/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_degraded_fields/index.ts b/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_degraded_fields/index.ts index 1c825e88bd693..61655ba3842c6 100644 --- a/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_degraded_fields/index.ts +++ b/x-pack/platform/plugins/shared/dataset_quality/server/routes/data_streams/get_degraded_fields/index.ts @@ -48,7 +48,7 @@ export async function getDegradedFields({ size: 1, field: INDEX, order: { - _key: 'desc', + _key: 'desc' as const, }, }, }, diff --git a/x-pack/platform/plugins/shared/entity_manager/server/lib/auth/privileges.ts b/x-pack/platform/plugins/shared/entity_manager/server/lib/auth/privileges.ts index 87f17b93ea57e..74a7fe4d8cb25 100644 --- a/x-pack/platform/plugins/shared/entity_manager/server/lib/auth/privileges.ts +++ b/x-pack/platform/plugins/shared/entity_manager/server/lib/auth/privileges.ts @@ -14,33 +14,33 @@ export const canManageEntityDefinition = async ( client: ElasticsearchClient, sourceIndices: string[] ) => { - const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges({ - body: entityDefinitionRuntimePrivileges(sourceIndices), - }); + const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges( + entityDefinitionRuntimePrivileges(sourceIndices) + ); return hasAllRequested; }; export const canDeleteEntityDefinition = async (client: ElasticsearchClient) => { - const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges({ - body: entityDefinitionDeletionPrivileges, - }); + const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges( + entityDefinitionDeletionPrivileges + ); return hasAllRequested; }; const canManageAPIKey = async (client: ElasticsearchClient) => { - const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges({ - body: apiKeyCreationPrivileges, - }); + const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges( + apiKeyCreationPrivileges + ); return hasAllRequested; }; const canDeleteAPIKey = async (client: ElasticsearchClient) => { - const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges({ - body: apiKeyDeletionPrivileges, - }); + const { has_all_requested: hasAllRequested } = await client.security.hasPrivileges( + apiKeyDeletionPrivileges + ); return hasAllRequested; }; diff --git a/x-pack/platform/plugins/shared/entity_manager/server/lib/v2/definitions/setup_entity_definitions_index.ts b/x-pack/platform/plugins/shared/entity_manager/server/lib/v2/definitions/setup_entity_definitions_index.ts index 05d7b2de7cb97..d69ecfd355c9a 100644 --- a/x-pack/platform/plugins/shared/entity_manager/server/lib/v2/definitions/setup_entity_definitions_index.ts +++ b/x-pack/platform/plugins/shared/entity_manager/server/lib/v2/definitions/setup_entity_definitions_index.ts @@ -34,16 +34,16 @@ const definitionsIndexTemplate = { dynamic: false, properties: { template_version: { - type: 'short', + type: 'short' as const, }, definition_type: { - type: 'keyword', + type: 'keyword' as const, }, source: { - type: 'object', + type: 'object' as const, properties: { type_id: { - type: 'keyword', + type: 'keyword' as const, }, }, }, diff --git a/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.test.ts index 830f5399a4aac..0a1684d34f085 100644 --- a/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.test.ts +++ b/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.test.ts @@ -20,7 +20,7 @@ import { import { AggregateOptionsType, queryOptionsSchema } from '../event_log_client'; import { delay } from '../lib/delay'; import { pick, times } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression } from '@kbn/es-query'; import { getEsNames } from './names'; @@ -443,7 +443,7 @@ describe('setIndexToHidden', () => { await clusterClientAdapter.setIndexToHidden('foo-bar-000001'); expect(clusterClient.indices.putSettings).toHaveBeenCalledWith({ index: 'foo-bar-000001', - body: { + settings: { index: { hidden: true, }, @@ -502,18 +502,16 @@ describe('setIndexAliasToHidden', () => { { alias: 'foo-bar', indexName: 'foo-bar-000001', is_write_index: true }, ]); expect(clusterClient.indices.updateAliases).toHaveBeenCalledWith({ - body: { - actions: [ - { - add: { - index: 'foo-bar-000001', - alias: 'foo-bar', - is_hidden: true, - is_write_index: true, - }, + actions: [ + { + add: { + index: 'foo-bar-000001', + alias: 'foo-bar', + is_hidden: true, + is_write_index: true, }, - ], - }, + }, + ], }); }); @@ -523,27 +521,25 @@ describe('setIndexAliasToHidden', () => { { alias: 'foo-bar', indexName: 'foo-bar-000002', index_routing: 'index', routing: 'route' }, ]); expect(clusterClient.indices.updateAliases).toHaveBeenCalledWith({ - body: { - actions: [ - { - add: { - index: 'foo-bar-000001', - alias: 'foo-bar', - is_hidden: true, - is_write_index: true, - }, + actions: [ + { + add: { + index: 'foo-bar-000001', + alias: 'foo-bar', + is_hidden: true, + is_write_index: true, }, - { - add: { - index: 'foo-bar-000002', - alias: 'foo-bar', - is_hidden: true, - index_routing: 'index', - routing: 'route', - }, + }, + { + add: { + index: 'foo-bar-000002', + alias: 'foo-bar', + is_hidden: true, + index_routing: 'index', + routing: 'route', }, - ], - }, + }, + ], }); }); @@ -777,12 +773,10 @@ describe('queryEventsBySavedObject', () => { index: 'index-name', track_total_hits: true, seq_no_primary_term: true, - body: { - size: 6, - from: 12, - query: getQueryBody(logger, options, pick(options.findOptions, ['start', 'end', 'filter'])), - sort: [{ '@timestamp': { order: 'asc' } }, { 'event.end': { order: 'desc' } }], - }, + size: 6, + from: 12, + query: getQueryBody(logger, options, pick(options.findOptions, ['start', 'end', 'filter'])), + sort: [{ '@timestamp': { order: 'asc' } }, { 'event.end': { order: 'desc' } }], }); expect(result).toEqual({ page: 3, @@ -851,19 +845,17 @@ describe('aggregateEventsBySavedObject', () => { const [query] = clusterClient.search.mock.calls[0]; expect(query).toEqual({ index: 'index-name', - body: { - size: 0, - query: getQueryBody( - logger, - options, - pick(options.aggregateOptions, ['start', 'end', 'filter']) - ), - aggs: { - genericAgg: { - term: { - field: 'event.action', - size: 10, - }, + size: 0, + query: getQueryBody( + logger, + options, + pick(options.aggregateOptions, ['start', 'end', 'filter']) + ), + aggs: { + genericAgg: { + term: { + field: 'event.action', + size: 10, }, }, }, @@ -956,19 +948,17 @@ describe('aggregateEventsWithAuthFilter', () => { const [query] = clusterClient.search.mock.calls[0]; expect(query).toEqual({ index: 'index-name', - body: { - size: 0, - query: getQueryBodyWithAuthFilter( - logger, - options, - pick(options.aggregateOptions, ['start', 'end', 'filter']) - ), - aggs: { - genericAgg: { - term: { - field: 'event.action', - size: 10, - }, + size: 0, + query: getQueryBodyWithAuthFilter( + logger, + options, + pick(options.aggregateOptions, ['start', 'end', 'filter']) + ), + aggs: { + genericAgg: { + term: { + field: 'event.action', + size: 10, }, }, }, @@ -1048,82 +1038,80 @@ describe('aggregateEventsWithAuthFilter', () => { const [query] = clusterClient.search.mock.calls[0]; expect(query).toEqual({ index: 'index-name', - body: { - size: 0, - query: { - bool: { - filter: { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - test: 'test', - }, + size: 0, + query: { + bool: { + filter: { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + test: 'test', }, - ], - }, + }, + ], }, - must: [ - { - nested: { - path: 'kibana.saved_objects', - query: { - bool: { - must: [ - { - term: { - 'kibana.saved_objects.rel': { - value: 'primary', - }, + }, + must: [ + { + nested: { + path: 'kibana.saved_objects', + query: { + bool: { + must: [ + { + term: { + 'kibana.saved_objects.rel': { + value: 'primary', }, }, - { - term: { - 'kibana.saved_objects.type': { - value: 'saved-object-type', - }, + }, + { + term: { + 'kibana.saved_objects.type': { + value: 'saved-object-type', }, }, - { - bool: { - should: [ - { - bool: { - should: [ - { - term: { - 'kibana.saved_objects.namespace': { - value: 'namespace', - }, + }, + { + bool: { + should: [ + { + bool: { + should: [ + { + term: { + 'kibana.saved_objects.namespace': { + value: 'namespace', }, }, - ], - }, + }, + ], }, - { - match: { - 'kibana.saved_objects.space_agnostic': true, - }, + }, + { + match: { + 'kibana.saved_objects.space_agnostic': true, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, }, }, - ], - }, + }, + ], }, + }, - aggs: { - genericAgg: { - term: { - field: 'event.action', - size: 10, - }, + aggs: { + genericAgg: { + term: { + field: 'event.action', + size: 10, }, }, }, diff --git a/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.ts b/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.ts index b1921ec029e35..852eb30636c68 100644 --- a/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.ts +++ b/x-pack/platform/plugins/shared/event_log/server/es/cluster_client_adapter.ts @@ -11,7 +11,7 @@ import { reject, isUndefined, isNumber, pick, isEmpty, get } from 'lodash'; import type { PublicMethodsOf } from '@kbn/utility-types'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; import util from 'util'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression, toElasticsearchQuery, KueryNode, nodeBuilder } from '@kbn/es-query'; import { BulkResponse, long } from '@elastic/elasticsearch/lib/api/types'; import { IEvent, IValidatedEvent, SAVED_OBJECT_REL_PRIMARY } from '../types'; @@ -323,6 +323,7 @@ export class ClusterClientAdapter< name: indexTemplateName, body: { ...currentIndexTemplate, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 settings: { ...currentIndexTemplate.settings, 'index.hidden': true, @@ -354,7 +355,7 @@ export class ClusterClientAdapter< const esClient = await this.elasticsearchClientPromise; await esClient.indices.putSettings({ index: indexName, - body: { + settings: { index: { hidden: true }, }, }); @@ -383,25 +384,23 @@ export class ClusterClientAdapter< try { const esClient = await this.elasticsearchClientPromise; await esClient.indices.updateAliases({ - body: { - actions: currentAliasData.map((aliasData) => { - const existingAliasOptions = pick(aliasData, [ - 'is_write_index', - 'filter', - 'index_routing', - 'routing', - 'search_routing', - ]); - return { - add: { - ...existingAliasOptions, - index: aliasData.indexName, - alias: aliasName, - is_hidden: true, - }, - }; - }), - }, + actions: currentAliasData.map((aliasData) => { + const existingAliasOptions = pick(aliasData, [ + 'is_write_index', + 'filter', + 'index_routing', + 'routing', + 'search_routing', + ]); + return { + add: { + ...existingAliasOptions, + index: aliasData.indexName, + alias: aliasName, + is_hidden: true, + }, + }; + }), }); } catch (err) { throw new Error( @@ -444,6 +443,7 @@ export class ClusterClientAdapter< const simulatedMapping = get(simulatedIndexMapping, ['template', 'mappings']); if (simulatedMapping != null) { + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 await esClient.indices.putMapping({ index: name, body: simulatedMapping }); this.logger.debug(`Successfully updated concrete index mappings for ${name}`); } @@ -467,7 +467,7 @@ export class ClusterClientAdapter< pick(queryOptions.findOptions, ['start', 'end', 'filter']) ); - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { size: perPage, from: (page - 1) * perPage, query, @@ -482,7 +482,7 @@ export class ClusterClientAdapter< index, track_total_hits: true, seq_no_primary_term: true, - body, + ...body, }); return { @@ -556,7 +556,7 @@ export class ClusterClientAdapter< pick(queryOptions.findOptions, ['start', 'end', 'filter']) ); - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { size: perPage, from: (page - 1) * perPage, query, @@ -571,7 +571,7 @@ export class ClusterClientAdapter< } = await esClient.search({ index, track_total_hits: true, - body, + ...body, seq_no_primary_term: true, }); return { @@ -607,7 +607,7 @@ export class ClusterClientAdapter< pick(queryOptions.aggregateOptions, ['start', 'end', 'filter']) ); - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { size: 0, query, aggs, @@ -616,7 +616,7 @@ export class ClusterClientAdapter< try { const { aggregations, hits } = await esClient.search({ index, - body, + ...body, }); return { aggregations, @@ -643,7 +643,7 @@ export class ClusterClientAdapter< pick(queryOptions.aggregateOptions, ['start', 'end', 'filter']) ); - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { size: 0, query, aggs, @@ -651,7 +651,7 @@ export class ClusterClientAdapter< try { const { aggregations, hits } = await esClient.search({ index, - body, + ...body, }); return { aggregations, diff --git a/x-pack/platform/plugins/shared/event_log/server/es/context.test.ts b/x-pack/platform/plugins/shared/event_log/server/es/context.test.ts index 4523a992df5be..cfe0f458bfc1a 100644 --- a/x-pack/platform/plugins/shared/event_log/server/es/context.test.ts +++ b/x-pack/platform/plugins/shared/event_log/server/es/context.test.ts @@ -9,7 +9,26 @@ import { createEsContext } from './context'; import { Logger } from '@kbn/core/server'; import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { createReadySignal } from '../lib/ready_signal'; -import { GetDataStreamsResponse } from './cluster_client_adapter.test'; +import type { estypes } from '@elastic/elasticsearch'; + +// Not importing because it'd run the tests in that file again +// import { GetDataStreamsResponse } from './cluster_client_adapter.test'; +export const GetDataStreamsResponse: estypes.IndicesGetDataStreamResponse = { + data_streams: [ + { + name: 'foo', + timestamp_field: { name: '@timestamp' }, + status: 'GREEN' as estypes.HealthStatus, + generation: 0, + indices: [], + template: '', + hidden: true, + prefer_ilm: false, + rollover_on_write: true, + next_generation_managed_by: 'Index Lifecycle Management', + }, + ], +}; jest.mock('../../../../../../package.json', () => ({ version: '1.2.3' })); jest.mock('./init'); diff --git a/x-pack/platform/plugins/shared/event_log/server/es/init.ts b/x-pack/platform/plugins/shared/event_log/server/es/init.ts index cd9b460b34553..faf1d484ffc5e 100644 --- a/x-pack/platform/plugins/shared/event_log/server/es/init.ts +++ b/x-pack/platform/plugins/shared/event_log/server/es/init.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { asyncForEach } from '@kbn/std'; import { groupBy } from 'lodash'; import pRetry, { FailedAttemptError } from 'p-retry'; diff --git a/x-pack/platform/plugins/shared/event_log/server/event_log_client.ts b/x-pack/platform/plugins/shared/event_log/server/event_log_client.ts index f6f61786a22fe..c9890e11622f4 100644 --- a/x-pack/platform/plugins/shared/event_log/server/event_log_client.ts +++ b/x-pack/platform/plugins/shared/event_log/server/event_log_client.ts @@ -9,7 +9,7 @@ import { omit } from 'lodash'; import { Observable } from 'rxjs'; import { schema, TypeOf } from '@kbn/config-schema'; import { IClusterClient, KibanaRequest } from '@kbn/core/server'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SpacesServiceStart } from '@kbn/spaces-plugin/server'; import { KueryNode } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/shared/fleet/common/types/models/epm.ts b/x-pack/platform/plugins/shared/fleet/common/types/models/epm.ts index 29b9c45e0e71d..512a37a327618 100644 --- a/x-pack/platform/plugins/shared/fleet/common/types/models/epm.ts +++ b/x-pack/platform/plugins/shared/fleet/common/types/models/epm.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { ASSETS_SAVED_OBJECT_TYPE, diff --git a/x-pack/platform/plugins/shared/fleet/server/integration_tests/upgrade_agent_policy_schema_version.test.ts b/x-pack/platform/plugins/shared/fleet/server/integration_tests/upgrade_agent_policy_schema_version.test.ts index 57e42a842a02c..51ca5b9afb358 100644 --- a/x-pack/platform/plugins/shared/fleet/server/integration_tests/upgrade_agent_policy_schema_version.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/integration_tests/upgrade_agent_policy_schema_version.test.ts @@ -180,7 +180,7 @@ describe('upgrade agent policy schema version', () => { esRes = await esClient.search({ index: AGENT_POLICY_INDEX, - body: { query: { match: { revision_idx: 2 } } }, + query: { match: { revision_idx: 2 } }, }); // since only 2 were updated, only 2 should be written expect((esRes.hits.total as SearchTotalHits).value).toBe(2); diff --git a/x-pack/platform/plugins/shared/fleet/server/routes/app/index.ts b/x-pack/platform/plugins/shared/fleet/server/routes/app/index.ts index a31eee8c03c55..94447568263be 100644 --- a/x-pack/platform/plugins/shared/fleet/server/routes/app/index.ts +++ b/x-pack/platform/plugins/shared/fleet/server/routes/app/index.ts @@ -55,7 +55,7 @@ export const getCheckPermissionsHandler: FleetRequestHandler< else if (request.query.fleetServerSetup && !isServerless) { const esClient = (await context.core).elasticsearch.client.asCurrentUser; const { has_all_requested: hasAllPrivileges } = await esClient.security.hasPrivileges({ - body: { cluster: ['manage_service_account'] }, + cluster: ['manage_service_account'], }); if (!hasAllPrivileges) { diff --git a/x-pack/platform/plugins/shared/fleet/server/routes/data_streams/get_data_streams_query_metadata.ts b/x-pack/platform/plugins/shared/fleet/server/routes/data_streams/get_data_streams_query_metadata.ts index fbaff4a7c8611..0073054bfadb2 100644 --- a/x-pack/platform/plugins/shared/fleet/server/routes/data_streams/get_data_streams_query_metadata.ts +++ b/x-pack/platform/plugins/shared/fleet/server/routes/data_streams/get_data_streams_query_metadata.ts @@ -38,17 +38,15 @@ export async function getDataStreamsQueryMetadata({ // it's just appended as a query string to the search operation and we can't // set `unmapped_type` for cases where `event.ingested` is not defiend, e.g. // in custom logs or custom HTTPJSON integrations - body: { - query: { - ...termsEnumIndexFilter, - }, - sort: { - 'event.ingested': { - order: 'desc', - // Necessary because of https://github.com/elastic/elasticsearch/issues/81960 - missing: 0, - unmapped_type: 'long', - }, + query: { + ...termsEnumIndexFilter, + }, + sort: { + 'event.ingested': { + order: 'desc', + // Necessary because of https://github.com/elastic/elasticsearch/issues/81960 + missing: 0, + unmapped_type: 'long', }, }, }), diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policies_to_agent_ids.ts b/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policies_to_agent_ids.ts index 0586f924633b6..e6d01a94e82d7 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policies_to_agent_ids.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policies_to_agent_ids.ts @@ -28,17 +28,15 @@ export const getAgentIdsForAgentPolicies = async ( ignore_unavailable: true, size: 100, // TODO: check if reasonable value _source: false, - body: { - query: { - bool: { - filter: [ - { - terms: { - policy_id: agentPolicyIds, - }, + query: { + bool: { + filter: [ + { + terms: { + policy_id: agentPolicyIds, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policy_agent_count.ts b/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policy_agent_count.ts index a87d249d647e3..6287e28a18f15 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policy_agent_count.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agent_policies/agent_policy_agent_count.ts @@ -29,33 +29,31 @@ export const getAgentCountForAgentPolicies = async ( >({ index: AGENTS_INDEX, ignore_unavailable: true, - body: { - query: { - bool: { - filter: [ - { - term: { - active: 'true', - }, + query: { + bool: { + filter: [ + { + term: { + active: 'true', }, - { - terms: { - policy_id: agentPolicyIds, - }, + }, + { + terms: { + policy_id: agentPolicyIds, }, - ], - }, - }, - aggs: { - agent_counts: { - terms: { - field: 'policy_id', - size: agentPolicyIds.length, }, + ], + }, + }, + aggs: { + agent_counts: { + terms: { + field: 'policy_id', + size: agentPolicyIds.length, }, }, - size: 0, }, + size: 0, }); const response: Record = agentPolicyIds.reduce>( diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agent_policy.ts b/x-pack/platform/plugins/shared/fleet/server/services/agent_policy.ts index 0010245a7aae7..12712bf752799 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agent_policy.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agent_policy.ts @@ -1484,15 +1484,13 @@ class AgentPolicyService { index: AGENT_POLICY_INDEX, ignore_unavailable: true, rest_total_hits_as_int: true, - body: { - query: { - term: { - policy_id: agentPolicyId, - }, + query: { + term: { + policy_id: agentPolicyId, }, - size: 1, - sort: [{ revision_idx: { order: 'desc' } }], }, + size: 1, + sort: [{ revision_idx: { order: 'desc' } }], }); if ((res.hits.total as number) === 0) { diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/action.mock.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/action.mock.ts index 50c2f0d6b0fbf..3872218c679e9 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/action.mock.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/action.mock.ts @@ -150,6 +150,7 @@ export function createClientMock() { { items: [] } ); + // @ts-expect-error not matching returned types esClientMock.mget.mockResponseImplementation((params) => { // @ts-expect-error const docs = params?.docs.map(({ _id }) => { diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/action_status.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/action_status.ts index d078620c30321..c5b5bfc60eeaa 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/action_status.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/action_status.ts @@ -240,9 +240,7 @@ async function getActions( from: 0, size: getPerPage(options), query: await addNamespaceFilteringToQuery(query, namespace), - body: { - sort: [{ '@timestamp': 'desc' }], - }, + sort: [{ '@timestamp': 'desc' }], }); return Object.values( diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/agent_service.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/agent_service.ts index b18394b0aea08..a11bd87b8a91d 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/agent_service.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/agent_service.ts @@ -15,7 +15,7 @@ import type { import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SortResults } from '@elastic/elasticsearch/lib/api/types'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/build_status_runtime_field.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/build_status_runtime_field.ts index 6cf7322715e18..87625d54b664e 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/build_status_runtime_field.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/build_status_runtime_field.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsClientContract } from '@kbn/core/server'; import type { Logger } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/crud.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/crud.ts index caf7ae42cbe4a..f57f58ba4a93b 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/crud.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/crud.ts @@ -6,7 +6,7 @@ */ import { groupBy } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SortResults } from '@elastic/elasticsearch/lib/api/types'; import type { SavedObjectsClientContract, ElasticsearchClient } from '@kbn/core/server'; import type { KueryNode } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/helpers.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/helpers.ts index 7e85df3422e55..26c08e2194409 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/helpers.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SortResults } from '@elastic/elasticsearch/lib/api/types'; import type { SearchHit } from '@kbn/es-types'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/reassign.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/reassign.test.ts index cf48ee20159f7..fc43cac915e48 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/reassign.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/reassign.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { HostedAgentPolicyRestrictionRelatedError } from '../../errors'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/request_diagnostics.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/request_diagnostics.test.ts index c6c3fc1622f20..c1954a4c01258 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/request_diagnostics.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/request_diagnostics.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { appContextService } from '../app_context'; import { createAppContextStartContractMock } from '../../mocks'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/status.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/status.ts index 175358019bfd1..dc541693a4ea5 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/status.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/status.ts @@ -194,14 +194,12 @@ export async function getIncomingDataByAgentsId({ try { const { has_all_requested: hasAllPrivileges } = await esClient.security.hasPrivileges({ - body: { - index: [ - { - names: [dataStreamPattern], - privileges: ['read'], - }, - ], - }, + index: [ + { + names: [dataStreamPattern], + privileges: ['read'], + }, + ], }); if (!hasAllPrivileges) { @@ -216,32 +214,30 @@ export async function getIncomingDataByAgentsId({ _source: returnDataPreview, timeout: '5s', size: returnDataPreview ? MAX_AGENT_DATA_PREVIEW_SIZE : 0, - body: { - query: { - bool: { - filter: [ - { - terms: { - 'agent.id': agentsIds, - }, + query: { + bool: { + filter: [ + { + terms: { + 'agent.id': agentsIds, }, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'now', - }, + }, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'now', }, }, - ], - }, - }, - aggs: { - agent_ids: { - terms: { - field: 'agent.id', - size: agentsIds.length, }, + ], + }, + }, + aggs: { + agent_ids: { + terms: { + field: 'agent.id', + size: agentsIds.length, }, }, }, diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/unenroll.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/unenroll.test.ts index 222d49ae44eed..44929545b6d3d 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/unenroll.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/unenroll.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { AGENT_ACTIONS_INDEX, AGENT_ACTIONS_RESULTS_INDEX } from '../../../common'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/upgrade.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/upgrade.test.ts index f39f557076283..f8dd108810b79 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/upgrade.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/upgrade.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { appContextService } from '../app_context'; import type { Agent } from '../../types'; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/agents/uploads.ts b/x-pack/platform/plugins/shared/fleet/server/services/agents/uploads.ts index 27d0a52eeb3c7..93173bf60f475 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/agents/uploads.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/agents/uploads.ts @@ -244,11 +244,9 @@ export async function deleteAgentUploadFile( const filesDeleteResponse = await esClient.deleteByQuery({ index: FILE_STORAGE_DATA_AGENT_INDEX, refresh: true, - body: { - query: { - match: { - bid: id, // Use `bid` instead of `_id` because `_id` has additional suffixes - }, + query: { + match: { + bid: id, // Use `bid` instead of `_id` because `_id` has additional suffixes }, }, }); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/api_keys/create_standalone_agent_api_key.ts b/x-pack/platform/plugins/shared/fleet/server/services/api_keys/create_standalone_agent_api_key.ts index 51cf0b7849a03..ef0c2c04052ae 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/api_keys/create_standalone_agent_api_key.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/api_keys/create_standalone_agent_api_key.ts @@ -25,16 +25,14 @@ export async function canCreateStandaloneAgentApiKey(esClient: ElasticsearchClie export function createStandaloneAgentApiKey(esClient: ElasticsearchClient, name: string) { // Based on https://www.elastic.co/guide/en/fleet/master/grant-access-to-elasticsearch.html#create-api-key-standalone-agent return esClient.security.createApiKey({ - body: { - name: `standalone_agent-${name}`, - metadata: { - managed: true, - }, - role_descriptors: { - standalone_agent: { - cluster: CLUSTER_PRIVILEGES, - indices: [INDEX_PRIVILEGES], - }, + name: `standalone_agent-${name}`, + metadata: { + managed: true, + }, + role_descriptors: { + standalone_agent: { + cluster: CLUSTER_PRIVILEGES, + indices: [INDEX_PRIVILEGES], }, }, }); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/platform/plugins/shared/fleet/server/services/api_keys/enrollment_api_key.ts index 6be0572b31bba..b95ea71c8e72d 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/api_keys/enrollment_api_key.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/api_keys/enrollment_api_key.ts @@ -78,10 +78,8 @@ export async function listEnrollmentApiKeys( track_total_hits: true, rest_total_hits_as_int: true, ignore_unavailable: true, - body: { - sort: [{ created_at: { order: 'desc' } }], - ...(query ? { query } : {}), - }, + sort: [{ created_at: { order: 'desc' } }], + ...(query ? { query } : {}), }); // @ts-expect-error @elastic/elasticsearch _source is optional @@ -172,10 +170,8 @@ export async function deleteEnrollmentApiKey( await esClient.update({ index: ENROLLMENT_API_KEYS_INDEX, id, - body: { - doc: { - active: false, - }, + doc: { + active: false, }, refresh: 'wait_for', }); @@ -272,27 +268,25 @@ export async function generateEnrollmentAPIKey( const key = await esClient.security .createApiKey({ - body: { - name, - metadata: { - managed_by: 'fleet', - managed: true, - type: 'enroll', - policy_id: data.agentPolicyId, - }, - role_descriptors: { - // Useless role to avoid to have the privilege of the user that created the key - 'fleet-apikey-enroll': { - cluster: [], - index: [], - applications: [ - { - application: 'fleet', - privileges: ['no-privileges'], - resources: ['*'], - }, - ], - }, + name, + metadata: { + managed_by: 'fleet', + managed: true, + type: 'enroll', + policy_id: data.agentPolicyId, + }, + role_descriptors: { + // Useless role to avoid to have the privilege of the user that created the key + 'fleet-apikey-enroll': { + cluster: [], + index: [], + applications: [ + { + application: 'fleet', + privileges: ['no-privileges'], + resources: ['*'], + }, + ], }, }, }) diff --git a/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.test.ts index 8c711099264f4..553d9c4402d30 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.test.ts @@ -437,9 +437,7 @@ describe('When using the artifacts services', () => { size: 20, track_total_hits: true, rest_total_hits_as_int: true, - body: { - sort: [{ created: { order: 'asc' } }], - }, + sort: [{ created: { order: 'asc' } }], }); expect(results).toEqual({ @@ -473,9 +471,7 @@ describe('When using the artifacts services', () => { size: 50, track_total_hits: true, rest_total_hits_as_int: true, - body: { - sort: [{ identifier: { order: 'desc' } }], - }, + sort: [{ identifier: { order: 'desc' } }], }); expect(listMeta).toEqual({ diff --git a/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.ts b/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.ts index c6173f1eb8e89..936e47a486884 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/artifacts/artifacts.ts @@ -253,9 +253,7 @@ export const listArtifacts = async ( size: perPage, track_total_hits: true, rest_total_hits_as_int: true, - body: { - sort: [{ [sortField]: { order: sortOrder } }], - }, + sort: [{ [sortField]: { order: sortOrder } }], }); return { diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/index/update_settings.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/index/update_settings.ts index 512a6661d80d5..74d3250c75c6c 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/index/update_settings.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/index/update_settings.ts @@ -25,7 +25,7 @@ export async function updateIndexSettings( await retryTransientEsErrors(() => esClient.indices.putSettings({ index, - body: settings, + settings, }) ); } catch (err) { diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/ml_model/install.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/ml_model/install.ts index 5057e5cfd68fe..e0c5d1b0088e4 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/ml_model/install.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/ml_model/install.ts @@ -86,8 +86,8 @@ async function handleMlModelInstall({ { model_id: mlModel.installationName, defer_definition_decompression: true, + // @ts-expect-error timeout is not declared timeout: '45s', - // @ts-expect-error expects an object not a string body: mlModel.content, }, { diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.test.ts index f735e8638b583..910d5b6cc98ca 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.test.ts @@ -129,7 +129,6 @@ describe('EPM index template install', () => { } expect(packageTemplate.settings?.index?.mapping).toHaveProperty('source'); - // @ts-expect-error esclient mapping out-of-date expect(packageTemplate.settings?.index?.mapping?.source).toEqual({ mode: 'synthetic' }); }); @@ -160,7 +159,6 @@ describe('EPM index template install', () => { } expect(packageTemplate.settings?.index?.mapping).toHaveProperty('source'); - // @ts-expect-error esclient mapping out-of-date expect(packageTemplate.settings?.index?.mapping?.source).toEqual({ mode: 'synthetic' }); }); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.ts index f17a05a6837aa..cac196fcb50c2 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/install.ts @@ -190,6 +190,7 @@ const installPreBuiltComponentTemplates = async ( }; return retryTransientEsErrors( + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 () => esClient.cluster.putComponentTemplate(esClientParams, { ignore: [404] }), { logger } ); @@ -652,6 +653,7 @@ async function installTemplate({ body: template.indexTemplate, }; await retryTransientEsErrors( + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 () => esClient.indices.putIndexTemplate(esClientParams, { ignore: [404] }), { logger } ); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/template.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/template.ts index 0506e92a9551a..79f90e1a202e1 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/template/template.ts @@ -1063,7 +1063,6 @@ const updateExistingDataStream = async ({ const existingDsConfig = Object.values(existingDs); const currentBackingIndexConfig = existingDsConfig.at(-1); const currentIndexMode = currentBackingIndexConfig?.settings?.index?.mode; - // @ts-expect-error Property 'source.mode' does not exist on type 'IndicesMappingLimitSettings' const currentSourceType = currentBackingIndexConfig?.settings?.index?.mapping?.source?.mode; let settings: IndicesIndexSettings; @@ -1108,7 +1107,8 @@ const updateExistingDataStream = async ({ () => esClient.indices.putMapping({ index: dataStreamName, - body: mappings || {}, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 + body: mappings, write_index_only: true, }), { logger } @@ -1163,7 +1163,6 @@ const updateExistingDataStream = async ({ // Trigger a rollover if the index mode or source type has changed if ( currentIndexMode !== settings?.index?.mode || - // @ts-expect-error Property 'source.mode' does not exist on type 'IndicesMappingLimitSettings' currentSourceType !== settings?.index?.mapping?.source?.mode || dynamicDimensionMappingsChanged ) { @@ -1218,7 +1217,7 @@ const updateExistingDataStream = async ({ () => esClient.indices.putSettings({ index: dataStreamName, - body: { default_pipeline: settings!.index!.default_pipeline }, + settings: { default_pipeline: settings!.index!.default_pipeline }, }), { logger } ); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/install.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/install.ts index 85ae293455c9e..4f1e3ab262772 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/install.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/install.ts @@ -732,7 +732,7 @@ async function handleTransformInstall({ { transform_id: transform.installationName, defer_validation: true, - body: transform.content, + ...transform.content, }, // add '{ headers: { es-secondary-authorization: 'ApiKey {encodedApiKey}' } }' { ignore: [409], ...(secondaryAuth ? { ...secondaryAuth } : {}) } diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/legacy_transforms.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/legacy_transforms.test.ts index 4b58dda7d0746..e705b10ebe011 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/legacy_transforms.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/legacy_transforms.test.ts @@ -201,7 +201,8 @@ describe('test transform install with legacy schema', () => { { transform_id: 'endpoint.metadata-default-0.16.0-dev.0', defer_validation: true, - body: { content: 'data', _meta: meta }, + content: 'data', + _meta: meta, }, { ignore: [409] }, ], @@ -209,7 +210,8 @@ describe('test transform install with legacy schema', () => { { transform_id: 'endpoint.metadata_current-default-0.16.0-dev.0', defer_validation: true, - body: { content: 'data', _meta: meta }, + content: 'data', + _meta: meta, }, { ignore: [409] }, ], @@ -351,7 +353,8 @@ describe('test transform install with legacy schema', () => { { transform_id: 'endpoint.metadata_current-default-0.16.0-dev.0', defer_validation: true, - body: { content: 'data', _meta: meta }, + content: 'data', + _meta: meta, }, { ignore: [409] }, ], @@ -577,7 +580,8 @@ describe('test transform install with legacy schema', () => { { transform_id: 'endpoint.metadata_current-default-0.16.0-dev.0', defer_validation: true, - body: { content: 'data', _meta: meta }, + content: 'data', + _meta: meta, }, { ignore: [409] }, ], diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/reauthorize.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/reauthorize.ts index 9a15763b3ddd9..88f5132ae2969 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/reauthorize.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/reauthorize.ts @@ -59,7 +59,7 @@ async function reauthorizeAndStartTransform({ esClient.transform.updateTransform( { transform_id: transformId, - body: { _meta: meta }, + _meta: meta, }, { ...(secondaryAuth ? secondaryAuth : {}) } ), diff --git a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/transforms.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/transforms.test.ts index 4d927ca4cef69..d5a41c1033710 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/transforms.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/epm/elasticsearch/transform/transforms.test.ts @@ -136,44 +136,42 @@ _meta: TRANSFORM: { transform_id: `logs-endpoint.metadata_current-default-${transformVersion}`, defer_validation: true, - body: { - description: 'Merges latest endpoint and Agent metadata documents.', - dest: { - index: '.metrics-endpoint.metadata_united_default', - aliases: [], - }, - frequency: '1s', - pivot: { - aggs: { - united: { - scripted_metric: { - combine_script: 'return state.docs', - init_script: 'state.docs = []', - map_script: "state.docs.add(new HashMap(params['_source']))", - reduce_script: - "def ret = new HashMap(); for (s in states) { for (d in s) { if (d.containsKey('Endpoint')) { ret.endpoint = d } else { ret.agent = d } }} return ret", - }, + description: 'Merges latest endpoint and Agent metadata documents.', + dest: { + index: '.metrics-endpoint.metadata_united_default', + aliases: [], + }, + frequency: '1s', + pivot: { + aggs: { + united: { + scripted_metric: { + combine_script: 'return state.docs', + init_script: 'state.docs = []', + map_script: "state.docs.add(new HashMap(params['_source']))", + reduce_script: + "def ret = new HashMap(); for (s in states) { for (d in s) { if (d.containsKey('Endpoint')) { ret.endpoint = d } else { ret.agent = d } }} return ret", }, }, - group_by: { - 'agent.id': { - terms: { - field: 'agent.id', - }, + }, + group_by: { + 'agent.id': { + terms: { + field: 'agent.id', }, }, }, - source: { - index: ['metrics-endpoint.metadata_current_default*', '.fleet-agents*'], - }, - sync: { - time: { - delay: '4s', - field: 'updated_at', - }, + }, + source: { + index: ['metrics-endpoint.metadata_current_default*', '.fleet-agents*'], + }, + sync: { + time: { + delay: '4s', + field: 'updated_at', }, - _meta: { fleet_transform_version: transformVersion, ...meta, run_as_kibana_system: true }, }, + _meta: { fleet_transform_version: transformVersion, ...meta, run_as_kibana_system: true }, }, }; }; diff --git a/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.test.ts index 0051418b1c00d..7384f30f18f0b 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.test.ts @@ -145,18 +145,16 @@ describe('FleetFromHostFilesClient', () => { await getFleetFilesInstance().doesFileHaveData('123'); expect(esClientMock.search).toHaveBeenCalledWith({ - body: { - _source: false, - query: { - bool: { - filter: [ - { - term: { - bid: '123', - }, + _source: false, + query: { + bool: { + filter: [ + { + term: { + bid: '123', }, - ], - }, + }, + ], }, }, index: '.fleet-fileds-fromhost-data-foo', diff --git a/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.ts b/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.ts index 4781f9467fb77..c47598798808c 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/files/client_from_host.ts @@ -9,7 +9,7 @@ import type { Readable } from 'stream'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import type { Logger } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { FileClient } from '@kbn/files-plugin/server'; import { createEsFileClient } from '@kbn/files-plugin/server'; @@ -54,12 +54,10 @@ export class FleetFromHostFilesClient implements FleetFromHostFileClientInterfac try { const fileDocSearchResult = await this.esClient.search({ index: this.fileMetaIndex, - body: { - size: 1, - query: { - term: { - _id: fileId, - }, + size: 1, + query: { + term: { + _id: fileId, }, }, }); @@ -94,21 +92,19 @@ export class FleetFromHostFilesClient implements FleetFromHostFileClientInterfac const chunks = await this.esClient.search({ index: this.fileDataIndex, size: 0, - body: { - query: { - bool: { - filter: [ - { - term: { - bid: fileId, - }, + query: { + bool: { + filter: [ + { + term: { + bid: fileId, }, - ], - }, + }, + ], }, - // Setting `_source` to false - we don't need the actual document to be returned - _source: false, }, + // Setting `_source` to false - we don't need the actual document to be returned + _source: false, }); return Boolean((chunks.hits?.total as estypes.SearchTotalHits)?.value); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/files/index.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/files/index.test.ts index 2991c1dcbd1a6..bd8a217ea132e 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/files/index.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/files/index.test.ts @@ -70,15 +70,13 @@ describe('files service', () => { expect(esClientMock.search).toBeCalledWith( { index: [FILE_STORAGE_METADATA_INDEX_PATTERN, FILE_STORAGE_TO_HOST_METADATA_INDEX_PATTERN], - body: { - size: ES_SEARCH_LIMIT, - query: { - term: { - 'file.Status': status, - }, + size: ES_SEARCH_LIMIT, + query: { + term: { + 'file.Status': status, }, - _source: false, }, + _source: false, ignore_unavailable: true, }, { signal: abortController.signal } @@ -134,26 +132,24 @@ describe('files service', () => { { ignore_unavailable: true, index: [FILE_STORAGE_DATA_INDEX_PATTERN, FILE_STORAGE_TO_HOST_DATA_INDEX_PATTERN], - body: { - size: ES_SEARCH_LIMIT, - query: { - bool: { - must: [ - { - terms: { - bid: Array.from(files.map((file) => file._id)), - }, + size: ES_SEARCH_LIMIT, + query: { + bool: { + must: [ + { + terms: { + bid: Array.from(files.map((file) => file._id)), }, - { - term: { - last: true, - }, + }, + { + term: { + last: true, }, - ], - }, + }, + ], }, - _source: ['bid'], }, + _source: ['bid'], }, { signal: abortController.signal } ); diff --git a/x-pack/platform/plugins/shared/fleet/server/services/files/index.ts b/x-pack/platform/plugins/shared/fleet/server/services/files/index.ts index 0598155153ce6..8aeafd2908166 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/files/index.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/files/index.ts @@ -42,15 +42,13 @@ export async function getFilesByStatus( .search( { index: [FILE_STORAGE_METADATA_INDEX_PATTERN, FILE_STORAGE_TO_HOST_METADATA_INDEX_PATTERN], - body: { - size: ES_SEARCH_LIMIT, - query: { - term: { - 'file.Status': status, - }, + size: ES_SEARCH_LIMIT, + query: { + term: { + 'file.Status': status, }, - _source: false, }, + _source: false, ignore_unavailable: true, }, { signal: abortController.signal } @@ -95,26 +93,24 @@ export async function fileIdsWithoutChunksByIndex( .search<{ bid: string }>( { index: [FILE_STORAGE_DATA_INDEX_PATTERN, FILE_STORAGE_TO_HOST_DATA_INDEX_PATTERN], - body: { - size: ES_SEARCH_LIMIT, - query: { - bool: { - must: [ - { - terms: { - bid: Array.from(allFileIds), - }, + size: ES_SEARCH_LIMIT, + query: { + bool: { + must: [ + { + terms: { + bid: Array.from(allFileIds), }, - { - term: { - last: true, - }, + }, + { + term: { + last: true, }, - ], - }, + }, + ], }, - _source: ['bid'], }, + _source: ['bid'], ignore_unavailable: true, }, { signal: abortController.signal } diff --git a/x-pack/platform/plugins/shared/fleet/server/services/package_policies/experimental_datastream_features.ts b/x-pack/platform/plugins/shared/fleet/server/services/package_policies/experimental_datastream_features.ts index 0877f38293f4e..af8352b639d75 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/package_policies/experimental_datastream_features.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/package_policies/experimental_datastream_features.ts @@ -192,6 +192,7 @@ export async function handleExperimentalDatastreamFeatureOptIn({ await esClient.cluster.putComponentTemplate({ name: componentTemplateName, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 body, _meta: { has_experimental_data_stream_indexing_features: hasExperimentalDataStreamIndexingFeatures, diff --git a/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.test.ts b/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.test.ts index c0ba9ab9e83d2..91c37651b3a0d 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.test.ts @@ -62,18 +62,16 @@ describe('updateDeprecatedComponentTemplates', () => { expect(esClientMock.cluster.putComponentTemplate).toHaveBeenCalledTimes(1); expect(esClientMock.cluster.putComponentTemplate).toHaveBeenCalledWith({ - body: { - template: { - mappings: { - _source: {}, - properties: {}, - }, - settings: { - index: { - mapping: { - source: { - mode: 'synthetic', - }, + template: { + mappings: { + _source: {}, + properties: {}, + }, + settings: { + index: { + mapping: { + source: { + mode: 'synthetic', }, }, }, diff --git a/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.ts b/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.ts index 6b963d5561b4c..c46127d31724f 100644 --- a/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.ts +++ b/x-pack/platform/plugins/shared/fleet/server/services/setup/update_deprecated_component_templates.ts @@ -34,30 +34,28 @@ export async function updateDeprecatedComponentTemplates(esClient: Elasticsearch async (componentTemplate) => { const source = componentTemplate.component_template.template.mappings!._source; const { mode, ...restOfSource } = source!; + // export type IndicesSourceMode = 'disabled' | 'stored' | 'synthetic'; + // export type MappingSourceFieldMode = 'disabled' | 'stored' | 'synthetic'; const settings = componentTemplate.component_template.template.settings; await esClient.cluster.putComponentTemplate({ name: componentTemplate.name, - body: { - template: { - settings: { - ...settings, - index: { - ...settings?.index, - mapping: { - ...settings?.index?.mapping, - // @ts-expect-error Property 'source' does not exist on type 'IndicesMappingLimitSettings' - source: { - // @ts-expect-error Property 'source.mode' does not exist on type 'IndicesMappingLimitSettings' - ...settings?.index?.mapping?.source, - mode, - }, + template: { + settings: { + ...settings, + index: { + ...settings?.index, + mapping: { + ...settings?.index?.mapping, + source: { + ...settings?.index?.mapping?.source, + mode: mode!, }, }, }, - mappings: { - ...componentTemplate.component_template.template.mappings, - _source: restOfSource, - }, + }, + mappings: { + ...componentTemplate.component_template.template.mappings, + _source: restOfSource, }, }, }); diff --git a/x-pack/platform/plugins/shared/fleet/server/tasks/delete_unenrolled_agents_task.ts b/x-pack/platform/plugins/shared/fleet/server/tasks/delete_unenrolled_agents_task.ts index 440567effac7d..c4c234ab7135e 100644 --- a/x-pack/platform/plugins/shared/fleet/server/tasks/delete_unenrolled_agents_task.ts +++ b/x-pack/platform/plugins/shared/fleet/server/tasks/delete_unenrolled_agents_task.ts @@ -108,18 +108,16 @@ export class DeleteUnenrolledAgentsTask { const response = await esClient.deleteByQuery( { index: AGENTS_INDEX, - body: { - query: { - bool: { - filter: [ - { - term: { - active: false, - }, + query: { + bool: { + filter: [ + { + term: { + active: false, }, - { exists: { field: 'unenrolled_at' } }, - ], - }, + }, + { exists: { field: 'unenrolled_at' } }, + ], }, }, }, diff --git a/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.test.ts b/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.test.ts index 07c1bf7ee8722..e258f8ab89765 100644 --- a/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.test.ts +++ b/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.test.ts @@ -156,29 +156,27 @@ describe('SyncIntegrationsTask', () => { expect(esClient.update).toHaveBeenCalledWith( { - body: { - doc: { - integrations: [ - { - package_name: 'package-1', - package_version: '0.1.0', - updated_at: expect.any(String), - }, - { - package_name: 'package-2', - package_version: '0.2.0', - updated_at: expect.any(String), - }, - ], - remote_es_hosts: [ - { hosts: ['https://remote1:9200'], name: 'remote1', sync_integrations: true }, - { hosts: ['https://remote2:9200'], name: 'remote2', sync_integrations: false }, - ], - }, - doc_as_upsert: true, - }, id: 'fleet-synced-integrations', index: 'fleet-synced-integrations', + doc: { + integrations: [ + { + package_name: 'package-1', + package_version: '0.1.0', + updated_at: expect.any(String), + }, + { + package_name: 'package-2', + package_version: '0.2.0', + updated_at: expect.any(String), + }, + ], + remote_es_hosts: [ + { hosts: ['https://remote1:9200'], name: 'remote1', sync_integrations: true }, + { hosts: ['https://remote2:9200'], name: 'remote2', sync_integrations: false }, + ], + }, + doc_as_upsert: true, }, expect.anything() ); diff --git a/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.ts b/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.ts index c7bebfc42e7f8..758759938fb6c 100644 --- a/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.ts +++ b/x-pack/platform/plugins/shared/fleet/server/tasks/sync_integrations_task.ts @@ -210,10 +210,8 @@ export class SyncIntegrationsTask { { id: FLEET_SYNCED_INTEGRATIONS_INDEX_NAME, index: FLEET_SYNCED_INTEGRATIONS_INDEX_NAME, - body: { - doc: newDoc, - doc_as_upsert: true, - }, + doc: newDoc, + doc_as_upsert: true, }, { signal: this.abortController.signal } ); diff --git a/x-pack/platform/plugins/shared/index_management/public/application/services/api.ts b/x-pack/platform/plugins/shared/index_management/public/application/services/api.ts index 96b21acb8f46a..5c818657c95bd 100644 --- a/x-pack/platform/plugins/shared/index_management/public/application/services/api.ts +++ b/x-pack/platform/plugins/shared/index_management/public/application/services/api.ts @@ -9,7 +9,7 @@ import { METRIC_TYPE } from '@kbn/analytics'; import type { SerializedEnrichPolicy } from '@kbn/index-management-shared-types'; import { IndicesStatsResponse } from '@elastic/elasticsearch/lib/api/types'; import { InferenceAPIConfigResponse } from '@kbn/ml-trained-models-utils'; -import { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { API_BASE_PATH, INTERNAL_API_BASE_PATH, diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/component_templates/register_update_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/component_templates/register_update_route.ts index 87ff780a5686a..b41558322da9f 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/component_templates/register_update_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/component_templates/register_update_route.ts @@ -6,7 +6,7 @@ */ import { schema } from '@kbn/config-schema'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { RouteDependencies } from '../../../types'; import { addBasePath } from '..'; @@ -45,12 +45,10 @@ export const registerUpdateRoute = ({ const responseBody = await client.asCurrentUser.cluster.putComponentTemplate({ name, - body: { - template: template as estypes.IndicesIndexState, - version, - _meta, - deprecated, - }, + template: template as estypes.IndicesIndexState, + version, + _meta, + deprecated, }); return response.ok({ body: responseBody }); diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_get_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_get_route.ts index a6ee8bb81c86c..a0ba7ea53504c 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_get_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_get_route.ts @@ -122,14 +122,12 @@ const getMeteringStats = (client: IScopedClusterClient, name?: string) => { const getDataStreamsPrivileges = (client: IScopedClusterClient, names: string[]) => { return client.asCurrentUser.security.hasPrivileges({ - body: { - index: [ - { - names, - privileges: ['delete_index', 'manage_data_stream_lifecycle'], - }, - ], - }, + index: [ + { + names, + privileges: ['delete_index', 'manage_data_stream_lifecycle'], + }, + ], }); }; diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_post_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_post_route.ts index 7d24b55fd08e7..ba12cdee88f86 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_post_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_post_route.ts @@ -59,7 +59,8 @@ export function registerPostOneApplyLatestMappings({ } await client.asCurrentUser.indices.putMapping({ index: name, - body: mappings || {}, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 + body: mappings, write_index_only: true, }); diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_put_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_put_route.ts index 5aec43ced0023..e17369a35422e 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_put_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/data_streams/register_put_route.ts @@ -55,7 +55,9 @@ export function registerPutDataRetention({ router, lib: { handleEsError } }: Rou const { headers } = await client.asCurrentUser.indices.putDataLifecycle( { name: dataStreams, - data_retention: dataRetention, + lifecycle: { + data_retention: dataRetention, + }, }, { meta: true } ); diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/helpers.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/helpers.ts index 534b0afd8e642..5104cb8967e92 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/helpers.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/helpers.ts @@ -9,7 +9,7 @@ import { forEach, keys, sortBy, reduce, size } from 'lodash'; import { flatMap, flow, groupBy, values as valuesFP, map, pickBy } from 'lodash/fp'; import type { IScopedClusterClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { FieldCapsResponse } from '@elastic/elasticsearch/lib/api/types'; export type FieldCapsList = FieldCapsResponse['fields']; @@ -119,14 +119,12 @@ export async function getIndices(dataClient: IScopedClusterClient, pattern: stri const response = await dataClient.asCurrentUser.search( { index: pattern, - body: { - size: 0, - aggs: { - indices: { - terms: { - field: '_index', - size: limit, - }, + size: 0, + aggs: { + indices: { + terms: { + field: '_index', + size: limit, }, }, }, diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/register_privileges_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/register_privileges_route.ts index 123785f827cfd..5cd58fcbb519e 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/register_privileges_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/enrich_policies/register_privileges_route.ts @@ -51,9 +51,7 @@ export const registerPrivilegesRoute = ({ try { const { has_all_requested: hasAllPrivileges, cluster } = await client.asCurrentUser.security.hasPrivileges({ - body: { - cluster: ['manage_enrich'], - }, + cluster: ['manage_enrich'], }); if (!hasAllPrivileges) { diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/settings/register_update_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/settings/register_update_route.ts index fa95f83f01d22..646601c088047 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/settings/register_update_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/settings/register_update_route.ts @@ -37,7 +37,7 @@ export function registerUpdateRoute({ router, lib: { handleEsError } }: RouteDep expand_wildcards: 'none' as const, reopen: true, index: indexName, - body: request.body, + settings: request.body, }; try { diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/stats/register_stats_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/stats/register_stats_route.ts index a24f9ec3f4f15..9e1775db41728 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/stats/register_stats_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/stats/register_stats_route.ts @@ -6,7 +6,7 @@ */ import { schema } from '@kbn/config-schema'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { RouteDependencies } from '../../../types'; import { addBasePath } from '..'; diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/lib.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/lib.ts index 757ba6fd6da7f..dad83bc901c65 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/lib.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/lib.ts @@ -6,6 +6,7 @@ */ import { IScopedClusterClient } from '@kbn/core/server'; +import type { IndicesPutIndexTemplateRequest } from '@elastic/elasticsearch/lib/api/types'; import { serializeTemplate, serializeLegacyTemplate } from '../../../../common/lib'; import { TemplateDeserialized, LegacyTemplateSerialized } from '../../../../common'; @@ -39,33 +40,18 @@ export const saveTemplate = async ({ : serializeTemplate(template); if (isLegacy) { - const { - order, - // eslint-disable-next-line @typescript-eslint/naming-convention - index_patterns, - version, - settings, - mappings, - aliases, - } = serializedTemplate as LegacyTemplateSerialized; + const { settings } = serializedTemplate as LegacyTemplateSerialized; return await client.asCurrentUser.indices.putTemplate({ name: template.name, - order, - body: { - index_patterns, - version, - // @ts-expect-error Types of property auto_expand_replicas are incompatible. - settings, - mappings, - aliases, - }, + ...serializedTemplate, + // @ts-expect-error Types of property auto_expand_replicas are incompatible. + settings, }); } return await client.asCurrentUser.indices.putIndexTemplate({ name: template.name, - // @ts-expect-error LegacyTemplateSerialized | TemplateSerialized conflicts with @elastic/elasticsearch IndicesPutIndexTemplateRequest - body: serializedTemplate, + ...(serializedTemplate as Omit), }); }; diff --git a/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/register_simulate_route.ts b/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/register_simulate_route.ts index ef19d2a3de8b8..fb2938bdbf11b 100644 --- a/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/register_simulate_route.ts +++ b/x-pack/platform/plugins/shared/index_management/server/routes/api/templates/register_simulate_route.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema, TypeOf } from '@kbn/config-schema'; import { RouteDependencies } from '../../../types'; diff --git a/x-pack/platform/plugins/shared/inference/scripts/evaluation/evaluation.ts b/x-pack/platform/plugins/shared/inference/scripts/evaluation/evaluation.ts index 425b7e334074a..85460d5fc207c 100644 --- a/x-pack/platform/plugins/shared/inference/scripts/evaluation/evaluation.ts +++ b/x-pack/platform/plugins/shared/inference/scripts/evaluation/evaluation.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { run } from '@kbn/dev-cli-runner'; import * as fastGlob from 'fast-glob'; import yargs from 'yargs'; @@ -36,6 +36,8 @@ function runEvaluations() { const kibanaClient = new KibanaClient(log, serviceUrls.kibanaUrl, argv.spaceId); const esClient = new Client({ node: serviceUrls.esUrl, + Connection: HttpConnection, + requestTimeout: 30_000, }); await kibanaClient.createSpaceIfNeeded(); diff --git a/x-pack/platform/plugins/shared/inference_endpoint/server/routes/index.ts b/x-pack/platform/plugins/shared/inference_endpoint/server/routes/index.ts index e634910300ae4..f09ca7527f84a 100644 --- a/x-pack/platform/plugins/shared/inference_endpoint/server/routes/index.ts +++ b/x-pack/platform/plugins/shared/inference_endpoint/server/routes/index.ts @@ -11,7 +11,7 @@ import { schema } from '@kbn/config-schema'; import { InferenceInferenceEndpointInfo, InferenceTaskType, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { InferenceServicesGetResponse } from '../types'; import { INFERENCE_ENDPOINT_INTERNAL_API_VERSION } from '../../common'; diff --git a/x-pack/platform/plugins/shared/ingest_pipelines/common/lib/pipeline_serialization.ts b/x-pack/platform/plugins/shared/ingest_pipelines/common/lib/pipeline_serialization.ts index cec58c103bacd..be5d023cf4b84 100644 --- a/x-pack/platform/plugins/shared/ingest_pipelines/common/lib/pipeline_serialization.ts +++ b/x-pack/platform/plugins/shared/ingest_pipelines/common/lib/pipeline_serialization.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { Pipeline, Processor } from '../types'; export function deserializePipelines(pipelinesByName: { diff --git a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/create.ts b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/create.ts index f43ccb7b4be81..8e9be65e30e12 100644 --- a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/create.ts +++ b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/create.ts @@ -67,13 +67,11 @@ export const registerCreateRoute = ({ try { const response = await clusterClient.asCurrentUser.ingest.putPipeline({ id: name, - body: { - description, - processors, - version, - on_failure, - _meta, - }, + description, + processors, + version, + on_failure, + _meta, }); return res.ok({ body: response }); diff --git a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/privileges.ts b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/privileges.ts index 418d8665f5817..0f0ca461cf1d9 100644 --- a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/privileges.ts +++ b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/privileges.ts @@ -60,7 +60,7 @@ export const registerPrivilegesRoute = ({ router, config }: RouteDependencies) = const requiredPrivileges = requiredPrivilegesMap[permissionsType]; const { has_all_requested: hasAllPrivileges, cluster } = await clusterClient.asCurrentUser.security.hasPrivileges({ - body: { cluster: requiredPrivileges }, + cluster: requiredPrivileges, }); if (!hasAllPrivileges) { diff --git a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/simulate.ts b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/simulate.ts index 1b598f9f17fcc..5d6746db4b425 100644 --- a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/simulate.ts +++ b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/simulate.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { API_BASE_PATH } from '../../../common/constants'; @@ -42,10 +42,8 @@ export const registerSimulateRoute = ({ try { const response = await clusterClient.asCurrentUser.ingest.simulate({ verbose, - body: { - pipeline, - docs: documents as estypes.IngestSimulateDocument[], - }, + pipeline, + docs: documents as estypes.IngestDocument[], }); return res.ok({ body: response }); diff --git a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/update.ts b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/update.ts index c14fd46bced88..a649b5b2f92bf 100644 --- a/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/update.ts +++ b/x-pack/platform/plugins/shared/ingest_pipelines/server/routes/api/update.ts @@ -47,13 +47,11 @@ export const registerUpdateRoute = ({ const response = await clusterClient.asCurrentUser.ingest.putPipeline({ id: name, - body: { - description, - processors, - version, - on_failure, - _meta, - }, + description, + processors, + version, + on_failure, + _meta, }); return res.ok({ body: response }); diff --git a/x-pack/platform/plugins/shared/lens/public/datasources/form_based/utils.tsx b/x-pack/platform/plugins/shared/lens/public/datasources/form_based/utils.tsx index fb280530ade58..46169233e242d 100644 --- a/x-pack/platform/plugins/shared/lens/public/datasources/form_based/utils.tsx +++ b/x-pack/platform/plugins/shared/lens/public/datasources/form_based/utils.tsx @@ -23,7 +23,7 @@ import { SearchResponseWarningsBadgePopoverContent, } from '@kbn/search-response-warnings'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { isQueryValid } from '@kbn/visualization-ui-components'; import { getOriginalId } from '@kbn/transpose-utils'; import type { DateRange } from '../../../common/types'; diff --git a/x-pack/platform/plugins/shared/lens/public/report_performance_metric_util.ts b/x-pack/platform/plugins/shared/lens/public/report_performance_metric_util.ts index 64465e8d20a18..83a3840bbb6dc 100644 --- a/x-pack/platform/plugins/shared/lens/public/report_performance_metric_util.ts +++ b/x-pack/platform/plugins/shared/lens/public/report_performance_metric_util.ts @@ -7,7 +7,7 @@ import { RequestStatus } from '@kbn/inspector-plugin/common'; import type { Adapters } from '@kbn/inspector-plugin/public'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; export interface ILensRequestPerformance { requestTimeTotal: number; diff --git a/x-pack/platform/plugins/shared/lens/public/types.ts b/x-pack/platform/plugins/shared/lens/public/types.ts index b135ce9b995de..bac8562a8f065 100644 --- a/x-pack/platform/plugins/shared/lens/public/types.ts +++ b/x-pack/platform/plugins/shared/lens/public/types.ts @@ -38,7 +38,7 @@ import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; import type { FieldFormatParams } from '@kbn/field-formats-plugin/common'; import type { SearchResponseWarning } from '@kbn/search-response-warnings'; import type { EuiButtonIconProps } from '@elastic/eui'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import React from 'react'; import { CellValueContext } from '@kbn/embeddable-plugin/public'; import { EventAnnotationGroupConfig } from '@kbn/event-annotation-common'; diff --git a/x-pack/platform/plugins/shared/license_management/server/lib/permissions.ts b/x-pack/platform/plugins/shared/license_management/server/lib/permissions.ts index f362a331c2aef..d1adbc0ae9b0b 100644 --- a/x-pack/platform/plugins/shared/license_management/server/lib/permissions.ts +++ b/x-pack/platform/plugins/shared/license_management/server/lib/permissions.ts @@ -22,9 +22,7 @@ export async function getPermissions({ isSecurityEnabled, client }: GetPermissio try { const response = await client.asCurrentUser.security.hasPrivileges({ - body: { - cluster: ['manage'], // License management requires "manage" cluster privileges - }, + cluster: ['manage'], // License management requires "manage" cluster privileges }); return { hasPermission: response.cluster.manage, diff --git a/x-pack/platform/plugins/shared/licensing/server/license_fetcher.test.ts b/x-pack/platform/plugins/shared/licensing/server/license_fetcher.test.ts index 9c97489cf5c85..8d3002981d97e 100644 --- a/x-pack/platform/plugins/shared/licensing/server/license_fetcher.test.ts +++ b/x-pack/platform/plugins/shared/licensing/server/license_fetcher.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { getLicenseFetcher } from './license_fetcher'; import { loggerMock, type MockedLogger } from '@kbn/logging-mocks'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; diff --git a/x-pack/platform/plugins/shared/licensing/server/license_fetcher.ts b/x-pack/platform/plugins/shared/licensing/server/license_fetcher.ts index 6357fb7170a4c..0ae49b8aaf08a 100644 --- a/x-pack/platform/plugins/shared/licensing/server/license_fetcher.ts +++ b/x-pack/platform/plugins/shared/licensing/server/license_fetcher.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { createHash } from 'crypto'; import pRetry from 'p-retry'; import stringify from 'json-stable-stringify'; diff --git a/x-pack/platform/plugins/shared/licensing/server/plugin.test.ts b/x-pack/platform/plugins/shared/licensing/server/plugin.test.ts index 87190d8450692..5d58199b2762b 100644 --- a/x-pack/platform/plugins/shared/licensing/server/plugin.test.ts +++ b/x-pack/platform/plugins/shared/licensing/server/plugin.test.ts @@ -7,7 +7,7 @@ import moment from 'moment'; import { BehaviorSubject, firstValueFrom, take, toArray } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ClusterClientMock, coreMock, diff --git a/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_error_rate_timeseries/get_logs_error_rate_timeseries.ts b/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_error_rate_timeseries/get_logs_error_rate_timeseries.ts index ac4f62932b64a..ccb92b96640eb 100644 --- a/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_error_rate_timeseries/get_logs_error_rate_timeseries.ts +++ b/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_error_rate_timeseries/get_logs_error_rate_timeseries.ts @@ -7,7 +7,7 @@ import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { AggregationOptionsByType, AggregationResultOf } from '@kbn/es-types'; import { ElasticsearchClient } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { getBucketSizeFromTimeRangeAndBucketCount } from '../../utils'; import { ERROR_LOG_LEVEL, LOG_LEVEL } from '../../es_fields'; import { kqlQuery } from '../../utils/es_queries'; diff --git a/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rate_timeseries/get_logs_rate_timeseries.ts b/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rate_timeseries/get_logs_rate_timeseries.ts index 9df26b48db098..0795648716490 100644 --- a/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rate_timeseries/get_logs_rate_timeseries.ts +++ b/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rate_timeseries/get_logs_rate_timeseries.ts @@ -7,7 +7,7 @@ import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { AggregationOptionsByType, AggregationResultOf } from '@kbn/es-types'; import { ElasticsearchClient } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { getBucketSizeFromTimeRangeAndBucketCount } from '../../utils'; import { kqlQuery } from '../../utils/es_queries'; diff --git a/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rates_service/index.ts b/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rates_service/index.ts index 1eeeb82ed0b92..eb89ad3f967c8 100644 --- a/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rates_service/index.ts +++ b/x-pack/platform/plugins/shared/logs_data_access/server/services/get_logs_rates_service/index.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { getLogErrorRate, getLogRatePerMinute } from '../../utils'; import { LOG_LEVEL } from '../../es_fields'; diff --git a/x-pack/platform/plugins/shared/logs_data_access/server/utils/es_queries.ts b/x-pack/platform/plugins/shared/logs_data_access/server/utils/es_queries.ts index 282b21af495c9..1e0e642b5307e 100644 --- a/x-pack/platform/plugins/shared/logs_data_access/server/utils/es_queries.ts +++ b/x-pack/platform/plugins/shared/logs_data_access/server/utils/es_queries.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { QueryDslQueryContainer } from '@kbn/data-views-plugin/common/types'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/shared/logs_shared/common/log_views/resolved_log_view.ts b/x-pack/platform/plugins/shared/logs_shared/common/log_views/resolved_log_view.ts index cd2354994db2c..3b80a6d659a52 100644 --- a/x-pack/platform/plugins/shared/logs_shared/common/log_views/resolved_log_view.ts +++ b/x-pack/platform/plugins/shared/logs_shared/common/log_views/resolved_log_view.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DataView, DataViewsContract, FieldSpec } from '@kbn/data-views-plugin/common'; import { LogSourcesService } from '@kbn/logs-data-access-plugin/common/services/log_sources_service/types'; import { TIEBREAKER_FIELD, TIMESTAMP_FIELD } from '../constants'; diff --git a/x-pack/platform/plugins/shared/logs_shared/common/search_strategies/log_entries/log_entries.ts b/x-pack/platform/plugins/shared/logs_shared/common/search_strategies/log_entries/log_entries.ts index f8daaa1b9227b..326265e998ee3 100644 --- a/x-pack/platform/plugins/shared/logs_shared/common/search_strategies/log_entries/log_entries.ts +++ b/x-pack/platform/plugins/shared/logs_shared/common/search_strategies/log_entries/log_entries.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import * as rt from 'io-ts'; import { logEntryAfterCursorRT, diff --git a/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/adapter_types.ts b/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/adapter_types.ts index 46e77f48d3f4b..f420eba17ad1c 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/adapter_types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { JsonArray, JsonValue } from '@kbn/utility-types'; import { RouteMethod } from '@kbn/core/server'; import { VersionedRouteConfig } from '@kbn/core-http-server'; diff --git a/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/kibana_framework_adapter.ts index ca635642f3462..9a23dee9e949a 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { TransportRequestParams } from '@elastic/elasticsearch'; import { CoreSetup, IRouter, RouteMethod } from '@kbn/core/server'; import { UI_SETTINGS } from '@kbn/data-plugin/server'; @@ -139,7 +139,7 @@ export class KibanaFramework { apiResult = elasticsearch.client.asCurrentUser.search({ ...params, ...frozenIndicesParams, - }); + } as estypes.SearchRequest); break; case 'msearch': apiResult = elasticsearch.client.asCurrentUser.msearch({ diff --git a/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts index e10d7d87fd0bf..05328d37c9023 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { JsonObject } from '@kbn/utility-types'; import { LogColumn, LogEntry, LogEntryCursor } from '../../../../common/log_entry'; import { diff --git a/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts b/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts index c2b966e86983f..f4fc265dec058 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts @@ -6,7 +6,7 @@ */ import * as rt from 'io-ts'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { commonSearchSuccessResponseFieldsRT } from '../../../../utils/elasticsearch_runtime_types'; diff --git a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entries_search_strategy.test.ts b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entries_search_strategy.test.ts index 0cb65a7f4d83b..10a0b26a10411 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entries_search_strategy.test.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entries_search_strategy.test.ts @@ -70,17 +70,15 @@ describe('LogEntries search strategy', () => { expect.objectContaining({ params: expect.objectContaining({ index: 'log-indices-*', - body: expect.objectContaining({ - fields: expect.arrayContaining(['event.dataset', 'message']), - runtime_mappings: { - runtime_field: { - type: 'keyword', - script: { - source: 'emit("runtime value")', - }, + fields: expect.arrayContaining(['event.dataset', 'message']), + runtime_mappings: { + runtime_field: { + type: 'keyword', + script: { + source: 'emit("runtime value")', }, }, - }), + }, }), }), expect.anything(), diff --git a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entry_search_strategy.test.ts b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entry_search_strategy.test.ts index 5a8cac9e223bb..678144d003dc7 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entry_search_strategy.test.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/log_entry_search_strategy.test.ts @@ -6,7 +6,7 @@ */ import { errors, TransportResult } from '@elastic/elasticsearch'; -import { AsyncSearchSubmitResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AsyncSearchSubmitResponse } from '@elastic/elasticsearch/lib/api/types'; import { elasticsearchServiceMock, httpServerMock, @@ -89,23 +89,21 @@ describe('LogEntry search strategy', () => { expect(esClient.asyncSearch.submit).toHaveBeenCalledWith( expect.objectContaining({ index: 'log-indices-*', - body: expect.objectContaining({ - track_total_hits: false, - terminate_after: 1, - query: { - ids: { - values: ['LOG_ENTRY_ID'], - }, + track_total_hits: false, + terminate_after: 1, + query: { + ids: { + values: ['LOG_ENTRY_ID'], }, - runtime_mappings: { - runtime_field: { - type: 'keyword', - script: { - source: 'emit("runtime value")', - }, + }, + runtime_mappings: { + runtime_field: { + type: 'keyword', + script: { + source: 'emit("runtime value")', }, }, - }), + }, }), expect.anything() ); diff --git a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entries.ts b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entries.ts index 18992448fdfcc..81f9a71a53017 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entries.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entries.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import * as rt from 'io-ts'; import { LogEntryAfterCursor, @@ -39,26 +39,24 @@ export const createGetLogEntriesQuery = ( return { index: logEntriesIndex, allow_no_indices: true, - body: { - size, - track_scores: false, - track_total_hits: false, - query: { - bool: { - filter: [ - ...(query ? [query] : []), - ...(highlightQuery ? [highlightQuery] : []), - ...createTimeRangeFilterClauses(startTimestamp, endTimestamp, timestampField), - ], - }, + size, + track_scores: false, + track_total_hits: false, + query: { + bool: { + filter: [ + ...(query ? [query] : []), + ...(highlightQuery ? [highlightQuery] : []), + ...createTimeRangeFilterClauses(startTimestamp, endTimestamp, timestampField), + ], }, - fields, - runtime_mappings: runtimeMappings, - _source: false, - ...createSortClause(sortDirection, timestampField, tiebreakerField), - ...createSearchAfterClause(cursor), - ...createHighlightClause(highlightQuery, fields), }, + fields, + runtime_mappings: runtimeMappings, + _source: false, + ...createSortClause(sortDirection, timestampField, tiebreakerField), + ...createSearchAfterClause(cursor), + ...createHighlightClause(highlightQuery, fields), }; }; diff --git a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entry.ts b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entry.ts index 575541f3f7931..dace9687de148 100644 --- a/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entry.ts +++ b/x-pack/platform/plugins/shared/logs_shared/server/services/log_entries/queries/log_entry.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import * as rt from 'io-ts'; import { jsonArrayRT } from '../../../../common/typed_json'; import { @@ -21,30 +21,28 @@ export const createGetLogEntryQuery = ( runtimeMappings?: estypes.MappingRuntimeFields ): estypes.AsyncSearchSubmitRequest => ({ index: logEntryIndex, - body: { - size: 1, - terminate_after: 1, - track_scores: false, - track_total_hits: false, - query: { - ids: { - values: [logEntryId], - }, + size: 1, + terminate_after: 1, + track_scores: false, + track_total_hits: false, + query: { + ids: { + values: [logEntryId], }, - fields: ['*'], - runtime_mappings: runtimeMappings, - sort: [ - { - [timestampField]: { - order: 'desc', - format: 'strict_date_optional_time_nanos', - numeric_type: 'date_nanos', - }, - }, - { [tiebreakerField]: 'desc' }, - ], - _source: false, }, + fields: ['*'], + runtime_mappings: runtimeMappings, + sort: [ + { + [timestampField]: { + order: 'desc', + format: 'strict_date_optional_time_nanos', + numeric_type: 'date_nanos', + }, + }, + { [tiebreakerField]: 'desc' }, + ], + _source: false, }); export const logEntryHitRT = rt.intersection([ diff --git a/x-pack/platform/plugins/shared/maps/common/descriptor_types/map_descriptor.ts b/x-pack/platform/plugins/shared/maps/common/descriptor_types/map_descriptor.ts index 66a47307eb585..c5c82af4887f2 100644 --- a/x-pack/platform/plugins/shared/maps/common/descriptor_types/map_descriptor.ts +++ b/x-pack/platform/plugins/shared/maps/common/descriptor_types/map_descriptor.ts @@ -7,7 +7,7 @@ /* eslint-disable @typescript-eslint/consistent-type-definitions */ -import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/types'; import { ReactNode } from 'react'; import { GeoJsonProperties } from 'geojson'; import { Geometry } from 'geojson'; diff --git a/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/elasticsearch_geo_utils.ts b/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/elasticsearch_geo_utils.ts index 7f688124dc9ef..b972cdec1ced8 100644 --- a/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/elasticsearch_geo_utils.ts +++ b/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/elasticsearch_geo_utils.ts @@ -6,7 +6,7 @@ */ import _ from 'lodash'; -import type { TopLeftBottomRightGeoBounds } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { TopLeftBottomRightGeoBounds } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { Feature, FeatureCollection, Geometry, Polygon, Point, Position } from 'geojson'; import { BBox } from '@turf/helpers'; diff --git a/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/spatial_filter_utils.ts b/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/spatial_filter_utils.ts index c8c939d2e9fe1..5e68328c1ef50 100644 --- a/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/spatial_filter_utils.ts +++ b/x-pack/platform/plugins/shared/maps/common/elasticsearch_util/spatial_filter_utils.ts @@ -12,7 +12,7 @@ import type { QueryDslGeoDistanceQuery, QueryDslGeoShapeFieldQuery, QueryDslGeoShapeQuery, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { Feature, Geometry, MultiPolygon, Polygon, Position } from 'geojson'; // @ts-expect-error diff --git a/x-pack/platform/plugins/shared/maps/common/i18n_getters.ts b/x-pack/platform/plugins/shared/maps/common/i18n_getters.ts index 1fe7f84ea9fbd..3b40091c8e37c 100644 --- a/x-pack/platform/plugins/shared/maps/common/i18n_getters.ts +++ b/x-pack/platform/plugins/shared/maps/common/i18n_getters.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; export function getDataSourceLabel() { diff --git a/x-pack/platform/plugins/shared/maps/common/mvt_request_body.ts b/x-pack/platform/plugins/shared/maps/common/mvt_request_body.ts index c4bde852c1f60..69f908e5a5347 100644 --- a/x-pack/platform/plugins/shared/maps/common/mvt_request_body.ts +++ b/x-pack/platform/plugins/shared/maps/common/mvt_request_body.ts @@ -6,10 +6,7 @@ */ import rison from '@kbn/rison'; -import type { - SearchMvtRequest, - SearchRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchMvtRequest, SearchRequest } from '@elastic/elasticsearch/lib/api/types'; import { RENDER_AS } from './constants'; export function getAggsTileRequest({ @@ -35,7 +32,7 @@ export function getAggsTileRequest({ y: number; z: number; }) { - const requestBody = rison.decode(risonRequestBody) as SearchRequest['body']; + const requestBody = rison.decode(risonRequestBody) as SearchRequest; if (!requestBody) { throw new Error('Required requestBody parameter not provided'); } @@ -55,7 +52,7 @@ export function getAggsTileRequest({ aggs: requestBody.aggs, runtime_mappings: requestBody.runtime_mappings, with_labels: hasLabels, - } as SearchMvtRequest['body'], + } as SearchMvtRequest, }; } @@ -78,7 +75,7 @@ export function getHitsTileRequest({ y: number; z: number; }) { - const requestBody = rison.decode(risonRequestBody) as SearchRequest['body']; + const requestBody = rison.decode(risonRequestBody) as SearchRequest; if (!requestBody) { throw new Error('Required requestBody parameter not provided'); } @@ -97,9 +94,9 @@ export function getHitsTileRequest({ // Used to fetch number of hits that correspondes with track_total_hits size, with_labels: hasLabels, - } as SearchMvtRequest['body']; + } as SearchMvtRequest; if (requestBody.fields) { - // @ts-expect-error SearchRequest['body'].fields and SearchMvtRequest['body'].fields types do not allign, even though they do in implemenation + // @ts-expect-error SearchRequest.fields and SearchMvtRequest.fields types do not align, even though they do in implementation tileRequestBody.fields = requestBody.fields; } if (requestBody.sort) { diff --git a/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/agg_field.ts b/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/agg_field.ts index 92136779ac763..9d3e6af69ca02 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/agg_field.ts +++ b/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/agg_field.ts @@ -10,7 +10,7 @@ import type { AggregationsExtendedStatsAggregation, AggregationsPercentilesAggregation, AggregationsTermsAggregation, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { AGG_TYPE } from '../../../../common/constants'; import { TileMetaFeature } from '../../../../common/descriptor_types'; import { CountAggField } from './count_agg_field'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/count_agg_field.ts b/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/count_agg_field.ts index 140f605832fca..ef16bf305ba4e 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/count_agg_field.ts +++ b/x-pack/platform/plugins/shared/maps/public/classes/fields/agg/count_agg_field.ts @@ -9,7 +9,7 @@ import type { AggregationsExtendedStatsAggregation, AggregationsPercentilesAggregation, AggregationsTermsAggregation, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { DataView } from '@kbn/data-plugin/common'; import { IESAggSource } from '../../sources/es_agg_source'; import { IVectorSource } from '../../sources/vector_source'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/fields/es_doc_field.ts b/x-pack/platform/plugins/shared/maps/public/classes/fields/es_doc_field.ts index f72e2dba45791..7868921e5bcec 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/fields/es_doc_field.ts +++ b/x-pack/platform/plugins/shared/maps/public/classes/fields/es_doc_field.ts @@ -11,7 +11,7 @@ import type { AggregationsExtendedStatsAggregation, AggregationsPercentilesAggregation, AggregationsTermsAggregation, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { FIELD_ORIGIN } from '../../../common/constants'; import { ESTooltipProperty } from '../tooltips/es_tooltip_property'; import { ITooltipProperty, TooltipProperty } from '../tooltips/tooltip_property'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/fields/field.ts b/x-pack/platform/plugins/shared/maps/public/classes/fields/field.ts index 28015e5749118..5ad0d35787a4f 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/fields/field.ts +++ b/x-pack/platform/plugins/shared/maps/public/classes/fields/field.ts @@ -9,7 +9,7 @@ import type { AggregationsExtendedStatsAggregation, AggregationsPercentilesAggregation, AggregationsTermsAggregation, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { TileMetaFeature } from '../../../common/descriptor_types'; import { FIELD_ORIGIN } from '../../../common/constants'; import { IVectorSource } from '../sources/vector_source'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/layers/wizards/new_vector_layer_wizard/create_new_index_pattern.ts b/x-pack/platform/plugins/shared/maps/public/classes/layers/wizards/new_vector_layer_wizard/create_new_index_pattern.ts index b6496c73d0cb0..79afedfd61257 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/layers/wizards/new_vector_layer_wizard/create_new_index_pattern.ts +++ b/x-pack/platform/plugins/shared/maps/public/classes/layers/wizards/new_vector_layer_wizard/create_new_index_pattern.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { getHttp } from '../../../../kibana_services'; import { CreateDocSourceResp } from '../../../../../common/types'; import { INDEX_SOURCE_API_PATH } from '../../../../../common/constants'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx b/x-pack/platform/plugins/shared/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx index d21836fa5d512..d32b4f11c2dd5 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx +++ b/x-pack/platform/plugins/shared/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx @@ -13,7 +13,7 @@ import { Feature } from 'geojson'; import type { AggregationsCompositeAggregate, SearchResponse, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { SearchResponseWarning } from '@kbn/search-response-warnings'; import type { KibanaExecutionContext } from '@kbn/core/public'; import { ISearchSource } from '@kbn/data-plugin/common/search/search_source'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/sources/es_pew_pew_source/es_pew_pew_source.tsx b/x-pack/platform/plugins/shared/maps/public/classes/sources/es_pew_pew_source/es_pew_pew_source.tsx index 9540a22bf6a4e..d26b8f6847e57 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/sources/es_pew_pew_source/es_pew_pew_source.tsx +++ b/x-pack/platform/plugins/shared/maps/public/classes/sources/es_pew_pew_source/es_pew_pew_source.tsx @@ -16,7 +16,7 @@ import type { AggregationsGeoBoundsAggregate, LatLonGeoLocation, TopLeftBottomRightGeoBounds, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { UpdateSourceEditor } from './update_source_editor'; diff --git a/x-pack/platform/plugins/shared/maps/public/classes/sources/es_search_source/es_search_source.tsx b/x-pack/platform/plugins/shared/maps/public/classes/sources/es_search_source/es_search_source.tsx index dffe9628f29ec..296447608d29e 100644 --- a/x-pack/platform/plugins/shared/maps/public/classes/sources/es_search_source/es_search_source.tsx +++ b/x-pack/platform/plugins/shared/maps/public/classes/sources/es_search_source/es_search_source.tsx @@ -7,7 +7,7 @@ import _ from 'lodash'; import React, { ReactElement } from 'react'; -import type { QueryDslFieldLookup } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslFieldLookup } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import type { SearchResponseWarning } from '@kbn/search-response-warnings'; import { GeoJsonProperties, Geometry, Position } from 'geojson'; diff --git a/x-pack/platform/plugins/shared/maps/public/components/draw_forms/geometry_filter_form/geometry_filter_form.tsx b/x-pack/platform/plugins/shared/maps/public/components/draw_forms/geometry_filter_form/geometry_filter_form.tsx index 55831d2b2e83a..5aab906b5d353 100644 --- a/x-pack/platform/plugins/shared/maps/public/components/draw_forms/geometry_filter_form/geometry_filter_form.tsx +++ b/x-pack/platform/plugins/shared/maps/public/components/draw_forms/geometry_filter_form/geometry_filter_form.tsx @@ -6,7 +6,7 @@ */ import React, { ChangeEvent, Component } from 'react'; -import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/types'; import { EuiForm, EuiFormRow, diff --git a/x-pack/platform/plugins/shared/maps/public/connected_components/mb_map/tooltip_control/features_tooltip/feature_geometry_filter_form.tsx b/x-pack/platform/plugins/shared/maps/public/connected_components/mb_map/tooltip_control/features_tooltip/feature_geometry_filter_form.tsx index 1e5b7bf969d00..615131b448199 100644 --- a/x-pack/platform/plugins/shared/maps/public/connected_components/mb_map/tooltip_control/features_tooltip/feature_geometry_filter_form.tsx +++ b/x-pack/platform/plugins/shared/maps/public/connected_components/mb_map/tooltip_control/features_tooltip/feature_geometry_filter_form.tsx @@ -6,10 +6,7 @@ */ import React, { Component } from 'react'; -import type { - GeoShapeRelation, - QueryDslFieldLookup, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { GeoShapeRelation, QueryDslFieldLookup } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { Filter } from '@kbn/es-query'; import { ActionExecutionContext, Action } from '@kbn/ui-actions-plugin/public'; diff --git a/x-pack/platform/plugins/shared/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.tsx b/x-pack/platform/plugins/shared/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.tsx index 097faaa773f4d..75d20c67ee443 100644 --- a/x-pack/platform/plugins/shared/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.tsx +++ b/x-pack/platform/plugins/shared/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.tsx @@ -6,7 +6,7 @@ */ import React, { Component } from 'react'; -import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { GeoShapeRelation } from '@elastic/elasticsearch/lib/api/types'; import { EuiButtonIcon, EuiPopover, diff --git a/x-pack/platform/plugins/shared/maps/server/data_indexing/create_doc_source.ts b/x-pack/platform/plugins/shared/maps/server/data_indexing/create_doc_source.ts index 12dc618a96578..422085d21216f 100644 --- a/x-pack/platform/plugins/shared/maps/server/data_indexing/create_doc_source.ts +++ b/x-pack/platform/plugins/shared/maps/server/data_indexing/create_doc_source.ts @@ -5,10 +5,7 @@ * 2.0. */ -import type { - IndicesCreateRequest, - MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, IScopedClusterClient } from '@kbn/core/server'; import { DataViewsCommonService } from '@kbn/data-plugin/server'; import { CreateDocSourceResp } from '../../common/types'; @@ -47,12 +44,11 @@ async function createIndex( mappings: MappingTypeMapping, asCurrentUser: ElasticsearchClient ) { - const body: IndicesCreateRequest['body'] = { + await asCurrentUser.indices.create({ + index: indexName, mappings: { ...DEFAULT_META, ...mappings, }, - }; - - await asCurrentUser.indices.create({ index: indexName, body }); + }); } diff --git a/x-pack/platform/plugins/shared/maps/server/mvt/mvt_routes.ts b/x-pack/platform/plugins/shared/maps/server/mvt/mvt_routes.ts index aa3f0c51f69ea..604b49c00b47f 100644 --- a/x-pack/platform/plugins/shared/maps/server/mvt/mvt_routes.ts +++ b/x-pack/platform/plugins/shared/maps/server/mvt/mvt_routes.ts @@ -13,7 +13,7 @@ import { CoreStart, KibanaRequest, KibanaResponseFactory, Logger } from '@kbn/co import { IRouter } from '@kbn/core/server'; import type { DataRequestHandlerContext } from '@kbn/data-plugin/server'; import { errors } from '@elastic/elasticsearch'; -import type { SearchMvtRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchMvtRequest } from '@elastic/elasticsearch/lib/api/types'; import { APP_ID, MVT_GETTILE_API_PATH, @@ -22,6 +22,8 @@ import { } from '../../common/constants'; import { getAggsTileRequest, getHitsTileRequest } from '../../common/mvt_request_body'; +type SearchMvtRequestBody = Omit; + const CACHE_TIMEOUT_SECONDS = 60 * 60; export function initMVTRoutes({ @@ -77,7 +79,10 @@ export function initMVTRoutes({ const y = parseInt((params as any).y, 10) as number; const z = parseInt((params as any).z, 10) as number; - let tileRequest: { path: string; body: SearchMvtRequest['body'] } = { + let tileRequest: { + path: string; + body: SearchMvtRequestBody; + } = { path: '', body: {}, }; @@ -162,7 +167,7 @@ export function initMVTRoutes({ const y = parseInt((params as any).y, 10) as number; const z = parseInt((params as any).z, 10) as number; - let tileRequest: { path: string; body: SearchMvtRequest['body'] } = { + let tileRequest: { path: string; body: SearchMvtRequestBody } = { path: '', body: {}, }; @@ -214,7 +219,7 @@ async function getTile({ path, }: { abortController: AbortController; - body: SearchMvtRequest['body']; + body: SearchMvtRequestBody; context: DataRequestHandlerContext; core: CoreStart; executionContext: KibanaExecutionContext; diff --git a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed.ts b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed.ts index b9868e72838d1..9a3492553bf48 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type DatafeedId = string; diff --git a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts index 3c7f8c51785d1..b107162b14ebc 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts @@ -5,6 +5,6 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type DatafeedStats = estypes.MlDatafeedStats; diff --git a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job.ts b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job.ts index 9bddc3b2e512f..6db85ebc16746 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; export type JobId = string; diff --git a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job_stats.ts b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job_stats.ts index 995bd1e6a14fc..d088166806f12 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job_stats.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/job_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type JobStats = estypes.MlJobStats; diff --git a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/model_snapshot.ts b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/model_snapshot.ts index 806aca3eb43ad..c614ec6400f6a 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/model_snapshot.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/model_snapshot.ts @@ -5,6 +5,6 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type ModelSnapshot = estypes.MlModelSnapshot; diff --git a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/summary_job.ts b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/summary_job.ts index 1609c473dffc1..0e3839bca57ec 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/summary_job.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/anomaly_detection_jobs/summary_job.ts @@ -5,10 +5,10 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Moment } from 'moment'; -import type { MlCustomSettings } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MlCustomSettings } from '@elastic/elasticsearch/lib/api/types'; import type { CombinedJob, CombinedJobWithStats } from './combined_job'; import type { MlAnomalyDetectionAlertRule } from '../alerts'; import type { MlJobBlocked } from './job'; diff --git a/x-pack/platform/plugins/shared/ml/common/types/calendars.ts b/x-pack/platform/plugins/shared/ml/common/types/calendars.ts index a5e019d700282..eb160d287a4b7 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/calendars.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/calendars.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type MlCalendarId = string; diff --git a/x-pack/platform/plugins/shared/ml/common/types/management.ts b/x-pack/platform/plugins/shared/ml/common/types/management.ts index 98d1fe166534d..2ff77aadf353c 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/management.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/management.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SummaryJobState } from './anomaly_detection_jobs/summary_job'; export interface AnomalyDetectionManagementItems { diff --git a/x-pack/platform/plugins/shared/ml/common/types/ml_server_info.ts b/x-pack/platform/plugins/shared/ml/common/types/ml_server_info.ts index f7c5b4dea1ff6..477b5c3b461c0 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/ml_server_info.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/ml_server_info.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface MlServerDefaults { anomaly_detectors: { diff --git a/x-pack/platform/plugins/shared/ml/common/types/results.ts b/x-pack/platform/plugins/shared/ml/common/types/results.ts index f6d8caaa512a6..357851d5c7244 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/results.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/results.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { LineAnnotationDatum, RectAnnotationDatum } from '@elastic/charts'; import type { ErrorType } from '@kbn/ml-error-utils'; import type { ES_AGGREGATION, ML_JOB_AGGREGATION } from '@kbn/ml-anomaly-utils'; diff --git a/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts b/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts index 95e7c4ddc5f7e..9cd3e5175c20a 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts @@ -4,11 +4,11 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { InferenceInferenceEndpointInfo, MlInferenceConfigCreateContainer, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { ModelDefinitionResponse, ModelState, @@ -182,18 +182,18 @@ export interface StartTrainedModelDeploymentResponse { export interface AllocatedModel { key: string; deployment_id: string; - allocation_status: { + allocation_status?: { target_allocation_count: number; state: string; allocation_count: number; }; - number_of_allocations: number; - threads_per_allocation: number; + number_of_allocations?: number; + threads_per_allocation?: number; /** * Not required for rendering in the Model stats */ model_id?: string; - state: string; + state?: string; reason?: string; model_size_bytes: number; required_native_memory_bytes: number; diff --git a/x-pack/platform/plugins/shared/ml/common/util/job_utils.ts b/x-pack/platform/plugins/shared/ml/common/util/job_utils.ts index cdde803a482e5..cbd92faed1b44 100644 --- a/x-pack/platform/plugins/shared/ml/common/util/job_utils.ts +++ b/x-pack/platform/plugins/shared/ml/common/util/job_utils.ts @@ -10,7 +10,7 @@ import semverGte from 'semver/functions/gte'; import type { Duration } from 'moment'; import moment from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import numeral from '@elastic/numeral'; import { i18n } from '@kbn/i18n'; @@ -629,7 +629,9 @@ export function basicJobValidation( if (skipMmlChecks === false) { // model memory limit const mml = job.analysis_limits && job.analysis_limits.model_memory_limit; - const { messages: mmlUnitMessages, valid: mmlUnitValid } = validateModelMemoryLimitUnits(mml); + const { messages: mmlUnitMessages, valid: mmlUnitValid } = validateModelMemoryLimitUnits( + mml as string | undefined + ); messages.push(...mmlUnitMessages); valid = valid && mmlUnitValid; @@ -714,7 +716,7 @@ export function validateModelMemoryLimit(job: Job, limits: MlServerLimits): Vali ) { if (typeof limits === 'object' && typeof limits.max_model_memory_limit !== 'undefined') { const max = limits.max_model_memory_limit.toUpperCase(); - const mml = job.analysis_limits.model_memory_limit.toUpperCase(); + const mml = (job.analysis_limits.model_memory_limit as string | undefined)?.toUpperCase(); // @ts-ignore const mmlBytes = numeral(mml).value(); diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/custom_urls/custom_url_editor/utils.ts b/x-pack/platform/plugins/shared/ml/public/application/components/custom_urls/custom_url_editor/utils.ts index d2dff81c32621..a55d4ffe343c8 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/custom_urls/custom_url_editor/utils.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/custom_urls/custom_url_editor/utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import moment, { type Moment } from 'moment'; import { cloneDeep } from 'lodash'; import type { SerializableRecord } from '@kbn/utility-types'; @@ -439,7 +439,7 @@ async function getAnomalyDetectionJobTestUrl( let testUrl = customUrl.url_value; // Query to look for the highest scoring anomaly. - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { query: { bool: { must: [{ term: { job_id: job.job_id } }, { term: { result_type: 'record' } }], @@ -454,12 +454,7 @@ async function getAnomalyDetectionJobTestUrl( let resp; try { - resp = await mlApi.results.anomalySearch( - { - body, - }, - [job.job_id] - ); + resp = await mlApi.results.anomalySearch(body, [job.job_id]); } catch (error) { // search may fail if the job doesn't already exist // ignore this error as the outer function call will raise a toast diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx index f23bc8eb9da01..f10a0d2a4ccde 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx @@ -7,7 +7,7 @@ import type { FC } from 'react'; import React, { useState, useEffect, useCallback, useMemo } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiCallOut, EuiSpacer, EuiLink } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx index 95f6d040be42a..418f2b49d59d2 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx @@ -27,7 +27,7 @@ import { import { FormattedMessage } from '@kbn/i18n-react'; import { extractErrorMessage } from '@kbn/ml-error-utils'; import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { debounce } from 'lodash'; import { useMlApi, useMlKibana } from '../../../contexts/kibana'; import { isValidIndexName } from '../../../../../common/util/es_utils'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx index b2b46d5d59ace..d0f7945d2af7b 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/components/test_pipeline.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { memo, useEffect, useCallback, useMemo, useState } from 'react'; import { css } from '@emotion/react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useEuiTheme, @@ -30,7 +30,7 @@ import { htmlIdGenerator, } from '@elastic/eui'; -import type { IngestSimulateDocument } from '@elastic/elasticsearch/lib/api/types'; +import type { IngestDocument } from '@elastic/elasticsearch/lib/api/types'; import { extractErrorProperties } from '@kbn/ml-error-utils'; import { i18n } from '@kbn/i18n'; @@ -91,7 +91,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { try { const result = await mlApi.trainedModels.trainedModelPipelineSimulate( pipelineConfig, - JSON.parse(sampleDocsString) as IngestSimulateDocument[] + JSON.parse(sampleDocsString) as IngestDocument[] ); setSimulatePipelineResult(result); } catch (error) { @@ -125,7 +125,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { const getDocs = useCallback( async (body: any) => { - let records: IngestSimulateDocument[] = []; + let records: IngestDocument[] = []; let resp; try { resp = await mlApi.esSearch(body); diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts index bbed6dbfe4faa..d8431af734b80 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import type { IngestInferenceProcessor } from '@elastic/elasticsearch/lib/api/types'; import type { SupportedPytorchTasksType } from '@kbn/ml-trained-models-utils'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx index bd79731f22e0f..bdb0beb27c0bd 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx @@ -9,7 +9,7 @@ import type { FC } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { css } from '@emotion/react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; import { useEuiFontSize, diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx index a52550759b0f0..45688685c7327 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useMemo, useState } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiAccordion, diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/analytics.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/analytics.ts index 3264c7cc11f7a..429310f5cb156 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/analytics.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/analytics.ts @@ -18,7 +18,7 @@ import { type TrackTotalHitsSearchResponse, ANALYSIS_CONFIG_TYPE, } from '@kbn/ml-data-frame-analytics-utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Dictionary } from '../../../../common/types/common'; import type { MlApi } from '../../services/ml_api_service'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/get_index_data.ts index 6e2cb20025e72..0312c6cebeb32 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { extractErrorMessage } from '@kbn/ml-error-utils'; import { type DataFrameAnalyticsConfig } from '@kbn/ml-data-frame-analytics-utils'; import type { EsSorting, UseDataGridReturnType } from '@kbn/ml-data-grid'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts index 4ca336a510c54..34681f4f4ff27 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ES_FIELD_TYPES } from '@kbn/field-types'; import { EVENT_RATE_FIELD_ID } from '@kbn/ml-anomaly-utils'; import { diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts index c0ca5f8d945f5..6769157c8987a 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts @@ -8,7 +8,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import useMountedState from 'react-use/lib/useMountedState'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiDataGridColumn } from '@elastic/eui'; import type { CoreSetup } from '@kbn/core/public'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_results.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_results.tsx index 853c6194f76f9..08f03c8f83a95 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_results.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_results.tsx @@ -38,7 +38,7 @@ import { type DataFrameAnalyticsConfig, } from '@kbn/ml-data-frame-analytics-utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SEARCH_QUERY_LANGUAGE } from '@kbn/ml-query-utils'; import { parseInterval } from '@kbn/ml-parse-interval'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx index 8a160e541bc1b..de53d52e48665 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useEffect, useMemo, useState } from 'react'; import { debounce } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiButtonGroup, EuiCode, EuiFlexGroup, EuiFlexItem, EuiInputPopover } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { fromKueryExpression, luceneStringToDsl, toElasticsearchQuery } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts index 8d2d70dd898a4..77fe78c65a777 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts @@ -33,7 +33,7 @@ import { type UseIndexDataReturnType, } from '@kbn/ml-data-grid'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import { DataLoader } from '../../../../../datavisualizer/index_based/data_loader'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/outlier_exploration.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/outlier_exploration.tsx index eaeebf8e9772a..0e1759fb99507 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/outlier_exploration.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/outlier_exploration.tsx @@ -13,7 +13,7 @@ import { EuiCallOut, EuiPanel, EuiSpacer, EuiText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isOutlierAnalysis, FEATURE_INFLUENCE } from '@kbn/ml-data-frame-analytics-utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useColorRange, COLOR_RANGE, diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts index 8c362cd1b06b4..080808ec62712 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts @@ -26,7 +26,7 @@ import { type UseIndexDataReturnType, } from '@kbn/ml-data-grid'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DataLoader } from '../../../../../datavisualizer/index_based/data_loader'; import { useColorRange, diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx index 935a1eecb8538..991ea5c395fe8 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx @@ -27,7 +27,7 @@ import { ANALYSIS_CONFIG_TYPE, } from '@kbn/ml-data-frame-analytics-utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import type { Eval } from '../../../../common'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/platform/plugins/shared/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index fcf4e1cb484c4..295fd07aad8f5 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -10,7 +10,7 @@ import { DEFAULT_SAMPLER_SHARD_SIZE } from '@kbn/ml-agg-utils'; import { OMIT_FIELDS } from '@kbn/ml-anomaly-utils'; import { type RuntimeMappings } from '@kbn/ml-runtime-field-utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IndexPatternTitle } from '../../../../../common/types/kibana'; import type { MlApi } from '../../../services/ml_api_service'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index a2c5f2dc3438a..ad54ddb80933f 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { DataView } from '@kbn/data-views-plugin/public'; import type { Field, Aggregation, SplitField } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index 3d659c7a96fd7..c99a81a92f60c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -361,7 +361,7 @@ export class JobCreator { this._job_config.analysis_limits && this._job_config.analysis_limits.model_memory_limit !== undefined ) { - return this._job_config.analysis_limits.model_memory_limit; + return this._job_config.analysis_limits.model_memory_limit as string; } else { return null; } diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_validator/util.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_validator/util.ts index 340ab047d6582..b61b2dde5156e 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_validator/util.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_validator/util.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { ALLOWED_DATA_UNITS, JOB_ID_MAX_LENGTH } from '@kbn/ml-validators'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/results_loader/searches.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/results_loader/searches.ts index f9aaa56f59c06..4c351c5c83e90 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/results_loader/searches.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/results_loader/searches.ts @@ -57,69 +57,67 @@ export function getScoresByRecord( mlApi.results .anomalySearch( { - body: { - size: 0, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:record', - }, + size: 0, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:record', }, - { - bool: { - must: [ - { - range: { - timestamp: { - gte: earliestMs, - lte: latestMs, - // @ts-ignore - format: 'epoch_millis', - }, + }, + { + bool: { + must: [ + { + range: { + timestamp: { + gte: earliestMs, + lte: latestMs, + // @ts-ignore + format: 'epoch_millis', }, }, - { - query_string: { - query: jobIdFilterStr, - }, + }, + { + query_string: { + query: jobIdFilterStr, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - aggs: { - detector_index: { - terms: { - field: 'detector_index', - order: { - recordScore: 'desc', + }, + aggs: { + detector_index: { + terms: { + field: 'detector_index', + order: { + recordScore: 'desc', + }, + }, + aggs: { + recordScore: { + max: { + field: 'record_score', }, }, - aggs: { - recordScore: { - max: { - field: 'record_score', + byTime: { + date_histogram: { + field: 'timestamp', + fixed_interval: `${intervalMs}ms`, + min_doc_count: 1, + extended_bounds: { + min: earliestMs, + max: latestMs, }, }, - byTime: { - date_histogram: { - field: 'timestamp', - fixed_interval: `${intervalMs}ms`, - min_doc_count: 1, - extended_bounds: { - min: earliestMs, - max: latestMs, - }, - }, - aggs: { - recordScore: { - max: { - field: 'record_score', - }, + aggs: { + recordScore: { + max: { + field: 'record_score', }, }, }, diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts index b871a47744dcd..0cf35e1a2128c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts @@ -10,7 +10,7 @@ import { mergeWith, uniqWith, isEqual } from 'lodash'; import type { IUiSettingsClient } from '@kbn/core/public'; import type { TimefilterContract } from '@kbn/data-plugin/public'; import { firstValueFrom } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { DashboardApi, DashboardLocatorParams, diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts index 06272a5db0ef2..28e5ddd01f439 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts @@ -13,7 +13,7 @@ import type { DataViewsContract } from '@kbn/data-views-plugin/public'; import type { TimeRange } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import { MLCATEGORY, ML_JOB_AGGREGATION } from '@kbn/ml-anomaly-utils'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { CREATED_BY_LABEL, DEFAULT_BUCKET_SPAN } from '../../../../../common/constants/new_job'; import { type CreateState, QuickJobCreatorBase } from '../job_from_dashboard/quick_create_job_base'; import type { MlApi } from '../../../services/ml_api_service'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/utils.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/utils.ts index cde9c58aa914b..2289a304240cc 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/utils.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/job_from_pattern_analysis/utils.ts @@ -6,7 +6,7 @@ */ import type { DataViewField, DataView } from '@kbn/data-views-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { SharePluginStart } from '@kbn/share-plugin/public'; import type { Query, TimeRange } from '@kbn/es-query'; import { ML_APP_LOCATOR } from '../../../../../common/constants/locator'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx index 51146ee8992dc..4bcaca2c50a7c 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FC } from 'react'; import React, { Fragment, useState, useContext, useEffect } from 'react'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts index e96643c7ba6c1..031db77e22787 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { cloneDeep } from 'lodash'; import rison from '@kbn/rison'; import { diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts index ce77b21a3bd34..9af0461260bb1 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IngestInferenceProcessor, IngestInferenceConfig, diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_pipeline_config.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_pipeline_config.ts index 9ae2fa0f3d168..92e256d77e654 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_pipeline_config.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_pipeline_config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { InferecePipelineCreationState } from './state'; export function getPipelineConfig(state: InferecePipelineCreationState): estypes.IngestPipeline { diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/state.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/state.ts index 586537222c3c5..cb1d701d6da4b 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/state.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/state.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IngestInferenceProcessor } from '@elastic/elasticsearch/lib/api/types'; import type { TrainedModelItem } from '../../../../common/types/trained_models'; import { getDefaultOnFailureConfiguration } from '../../components/ml_inference/state'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/test_trained_model.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/test_trained_model.tsx index ba25e3b26f920..134f7772454ac 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/test_trained_model.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/test_trained_model.tsx @@ -10,7 +10,7 @@ import React from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiLink, EuiSpacer, EuiText, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TrainedModelItem } from '../../../../common/types/trained_models'; import { TestTrainedModelContent } from '../test_models/test_trained_model_content'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/deployment_params_mapper.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/deployment_params_mapper.ts index 96ba5f0755caa..d9bdeae9ec94d 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/deployment_params_mapper.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/deployment_params_mapper.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MlStartTrainedModelDeploymentRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MlStartTrainedModelDeploymentRequest } from '@elastic/elasticsearch/lib/api/types'; import type { NLPSettings } from '../../../common/constants/app'; import type { TrainedModelDeploymentStatsResponse } from '../../../common/types/trained_models'; import type { CloudInfo } from '../services/ml_server_info'; @@ -226,16 +226,16 @@ export class DeploymentParamsMapper { input: MlTrainedModelAssignmentTaskParametersAdaptive ): DeploymentParamsUI { let optimized: DeploymentParamsUI['optimized'] = 'optimizedForIngest'; - if (input.threads_per_allocation > 1) { + if (input.threads_per_allocation && input.threads_per_allocation > 1) { optimized = 'optimizedForSearch'; } const adaptiveResources = !!input.adaptive_allocations?.enabled; const vCPUs = - input.threads_per_allocation * + (input.threads_per_allocation ?? 0) * (adaptiveResources ? input.adaptive_allocations!.max_number_of_allocations! - : input.number_of_allocations); + : input.number_of_allocations ?? 0); // The deployment can be created via API with a number of allocations that do not exactly match our vCPU ranges. // In this case, we should find the closest vCPU range that does not exceed the max or static value of the range. diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/expanded_row.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/expanded_row.tsx index 4304e9e207e20..3360d5a022599 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/expanded_row.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/expanded_row.tsx @@ -199,7 +199,7 @@ export const ExpandedRow: FC = ({ item }) => { average_inference_time_ms: 0, inference_count: 0, routing_state: { - routing_state: perDeploymentStat.state, + routing_state: perDeploymentStat.state!, reason: perDeploymentStat.reason, }, last_access: 0, @@ -215,12 +215,11 @@ export const ExpandedRow: FC = ({ item }) => { } return perDeploymentStat.nodes.map((n) => { - const nodeName = Object.values(n.node)[0].name; + const nodeName = Object.values(n.node || {})[0]?.name; return { key: `${perDeploymentStat.deployment_id}_${nodeName}`, ...perDeploymentStat, ...modelSizeStats, - // @ts-expect-error `throughput_last_minute` is not declared in ES Types node: { ...pick(n, [ 'average_inference_time_ms', diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/inference_api_tab.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/inference_api_tab.tsx index 3f55871a93e44..476220d4ce7b6 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/inference_api_tab.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/inference_api_tab.tsx @@ -16,7 +16,7 @@ import { EuiTitle, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; -import type { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/types'; export interface InferenceAPITabProps { inferenceApis: InferenceInferenceEndpointInfo[]; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts index eee0a38e0731b..200e62a1c5e69 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts @@ -7,7 +7,7 @@ import type { Observable } from 'rxjs'; import { BehaviorSubject, combineLatest, Subscription } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { map } from 'rxjs'; @@ -325,7 +325,7 @@ export abstract class InferenceBase { } protected async runPipelineSimulate( - processResponse: (d: estypes.IngestSimulateDocumentSimulation) => TInferResponse + processResponse: (d: estypes.IngestDocumentSimulation) => TInferResponse ): Promise { try { this.setRunning(); @@ -376,11 +376,10 @@ export abstract class InferenceBase { }; } - protected getDocFromResponse({ doc, error }: estypes.IngestSimulatePipelineSimulation) { + protected getDocFromResponse({ doc, error }: estypes.IngestSimulateDocumentResult) { if (doc === undefined) { if (error) { - // @ts-expect-error Error is now typed in estypes. However, I doubt that it doesn't get the HTTP wrapper expected. - this.setFinishedWithErrors(error); + this.setFinishedWithErrors(error as unknown as MLHttpFetchError); throw Error(error.reason); } diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_inference.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_inference.ts index d49db2d03fe01..2bc31b396e32a 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_inference.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_inference.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { SUPPORTED_PYTORCH_TASKS } from '@kbn/ml-trained-models-utils'; import type { trainedModelsApiProvider } from '../../../../services/ml_api_service/trained_models'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx index aa79f40dac7c8..3f5f13ef89eb2 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/ner/ner_output.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FC, PropsWithChildren } from 'react'; import React from 'react'; import useObservable from 'react-use/lib/useObservable'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/raw_output.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/raw_output.tsx index cb727d9139df6..59c9e98bf452e 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/raw_output.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/raw_output.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FC } from 'react'; import React from 'react'; import type { Observable } from 'rxjs'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_classification/common.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_classification/common.ts index 1c14a3366d4c1..876f706ae56bc 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_classification/common.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_classification/common.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { InferResponse } from '../inference_base'; const PROBABILITY_SIG_FIGS = 3; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_expansion/text_expansion_inference.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_expansion/text_expansion_inference.ts index d1e322e5d5d32..588946f55e912 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_expansion/text_expansion_inference.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/text_expansion/text_expansion_inference.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { SUPPORTED_PYTORCH_TASKS } from '@kbn/ml-trained-models-utils'; import { BehaviorSubject } from 'rxjs'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/selected_model.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/selected_model.tsx index 598bd206608c6..be6a811db46ee 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/selected_model.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/selected_model.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FC } from 'react'; import React, { useMemo, useEffect } from 'react'; import { cloneDeep } from 'lodash'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_model_content.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_model_content.tsx index 3c829c8f7cd49..608d5bb967b60 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_model_content.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_model_content.tsx @@ -11,7 +11,7 @@ import React, { useState, useMemo } from 'react'; import { SUPPORTED_PYTORCH_TASKS } from '@kbn/ml-trained-models-utils'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiFormRow, EuiSelect, EuiSpacer, EuiTab, EuiTabs, useEuiPaddingSize } from '@elastic/eui'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TrainedModelItem } from '../../../../common/types/trained_models'; import { isNLPModelItem } from '../../../../common/types/trained_models'; import { SelectedModel } from './selected_model'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_models_context.tsx b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_models_context.tsx index af943ebfeac43..f8529cef2b359 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_models_context.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/test_trained_models_context.tsx @@ -7,7 +7,7 @@ import type { Dispatch } from 'react'; import { createContext, useContext } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface TestTrainedModelsContextType { pipelineConfig?: estypes.IngestPipeline; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/trained_models_service.test.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/trained_models_service.test.ts index a0dd84216879e..c7235bb4850b2 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/trained_models_service.test.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/trained_models_service.test.ts @@ -43,6 +43,8 @@ describe('TrainedModelsService', () => { queue_capacity: 1024, deployment_id: 'my-deployment-id', cache_size: '1mb', + per_deployment_memory_bytes: '1mb', + per_allocation_memory_bytes: '1mb', }, node_count: 1, routing_table: { diff --git a/x-pack/platform/plugins/shared/ml/public/application/services/forecast_service.ts b/x-pack/platform/plugins/shared/ml/public/application/services/forecast_service.ts index ddce5e0b69f44..eed9c5990edcb 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/services/forecast_service.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/services/forecast_service.ts @@ -8,7 +8,7 @@ // Service for carrying out requests to run ML forecasts and to obtain // data on forecasts that have been performed. import { useMemo } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { get, find, each } from 'lodash'; import { map } from 'rxjs'; import type { MlApi } from './ml_api_service'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/index.ts b/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/index.ts index 3552b8f006091..1bef7f74cd700 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/index.ts @@ -7,7 +7,7 @@ import type { Observable } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RuntimeMappings } from '@kbn/ml-runtime-field-utils'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/inference_models.ts b/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/inference_models.ts index 140c373f95715..a1d3b7acf1f4e 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/inference_models.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/inference_models.ts @@ -6,7 +6,7 @@ */ import type { estypes } from '@elastic/elasticsearch'; -import type { InferenceTaskType } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { InferenceTaskType } from '@elastic/elasticsearch/lib/api/types'; import type { ModelConfig } from '@kbn/inference_integration_flyout/types'; import type { HttpService } from '../http_service'; import { ML_INTERNAL_BASE_PATH } from '../../../../common/constants/app'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/trained_models.ts b/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/trained_models.ts index 045eac4676340..28439ff7912b6 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/trained_models.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/services/ml_api_service/trained_models.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IngestPipeline } from '@elastic/elasticsearch/lib/api/types'; import { useMemo } from 'react'; @@ -277,7 +277,7 @@ export function trainedModelsApiProvider(httpService: HttpService) { inferTrainedModel( modelId: string, deploymentsId: string, - payload: estypes.MlInferTrainedModelRequest['body'], + payload: Omit, timeout?: string ) { const body = JSON.stringify(payload); @@ -290,10 +290,7 @@ export function trainedModelsApiProvider(httpService: HttpService) { }); }, - trainedModelPipelineSimulate( - pipeline: estypes.IngestPipeline, - docs: estypes.IngestSimulateDocument[] - ) { + trainedModelPipelineSimulate(pipeline: estypes.IngestPipeline, docs: estypes.IngestDocument[]) { const body = JSON.stringify({ pipeline, docs, diff --git a/x-pack/platform/plugins/shared/ml/public/application/services/results_service/result_service_rx.ts b/x-pack/platform/plugins/shared/ml/public/application/services/results_service/result_service_rx.ts index 0f6e31ea96e95..4451683f52bdf 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/services/results_service/result_service_rx.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/services/results_service/result_service_rx.ts @@ -319,49 +319,47 @@ export function resultsServiceRxProvider(mlApi: MlApi) { return mlApi.results .anomalySearch$( { - body: { - size: 0, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:model_plot', - analyze_wildcard: true, - }, + size: 0, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:model_plot', + analyze_wildcard: true, }, - { - bool: { - must: mustCriteria, - should: shouldCriteria, - minimum_should_match: 1, - }, + }, + { + bool: { + must: mustCriteria, + should: shouldCriteria, + minimum_should_match: 1, }, - ], - }, - }, - aggs: { - times: { - date_histogram: { - field: 'timestamp', - fixed_interval: `${intervalMs}ms`, - min_doc_count: 0, }, - aggs: { - actual: { - avg: { - field: 'actual', - }, + ], + }, + }, + aggs: { + times: { + date_histogram: { + field: 'timestamp', + fixed_interval: `${intervalMs}ms`, + min_doc_count: 0, + }, + aggs: { + actual: { + avg: { + field: 'actual', }, - modelUpper: { - [modelAggs.max]: { - field: 'model_upper', - }, + }, + modelUpper: { + [modelAggs.max]: { + field: 'model_upper', }, - modelLower: { - [modelAggs.min]: { - field: 'model_lower', - }, + }, + modelLower: { + [modelAggs.min]: { + field: 'model_lower', }, }, }, @@ -472,27 +470,25 @@ export function resultsServiceRxProvider(mlApi: MlApi) { return mlApi.results .anomalySearch$( { - body: { - size: maxResults !== undefined ? maxResults : 100, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:record', - analyze_wildcard: false, - }, + size: maxResults !== undefined ? maxResults : 100, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:record', + analyze_wildcard: false, }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - }, + }, + ], }, - sort: [{ record_score: { order: 'desc' } }], }, + sort: [{ record_score: { order: 'desc' } }], }, jobIds ) @@ -558,45 +554,43 @@ export function resultsServiceRxProvider(mlApi: MlApi) { return mlApi.results .anomalySearch$( { - body: { - size: 0, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:bucket', - analyze_wildcard: false, - }, + size: 0, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:bucket', + analyze_wildcard: false, }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - }, - }, - aggs: { - jobs: { - terms: { - field: 'job_id', - min_doc_count: 1, - size: maxJobs, }, - aggs: { - times: { - date_histogram: { - field: 'timestamp', - fixed_interval: `${intervalMs}ms`, - min_doc_count: 1, - }, - aggs: { - events: { - terms: { - field: 'scheduled_events', - size: maxEvents, - }, + ], + }, + }, + aggs: { + jobs: { + terms: { + field: 'job_id', + min_doc_count: 1, + size: maxJobs, + }, + aggs: { + times: { + date_histogram: { + field: 'timestamp', + fixed_interval: `${intervalMs}ms`, + min_doc_count: 1, + }, + aggs: { + events: { + terms: { + field: 'scheduled_events', + size: maxEvents, }, }, }, @@ -737,27 +731,25 @@ export function resultsServiceRxProvider(mlApi: MlApi) { return mlApi.results .anomalySearch$( { - body: { - size: maxResults !== undefined ? maxResults : 100, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:record', - analyze_wildcard: false, - }, + size: maxResults !== undefined ? maxResults : 100, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:record', + analyze_wildcard: false, }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - }, + }, + ], }, - sort: [{ record_score: { order: 'desc' } }], }, + sort: [{ record_score: { order: 'desc' } }], }, jobIds ) diff --git a/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/calendar_form.tsx b/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/calendar_form.tsx index 5d8e02b8056a1..9abc340ff445a 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/calendar_form.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/calendar_form.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useState, useCallback } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiSwitchEvent, EuiComboBoxOptionOption } from '@elastic/eui'; import { EuiButton, diff --git a/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/dst_event_generator.tsx b/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/dst_event_generator.tsx index 914a22856c89a..320d0edbe42cf 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/dst_event_generator.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/calendar_form/dst_event_generator.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; import { EuiCallOut, diff --git a/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/events_table/events_table.tsx b/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/events_table/events_table.tsx index 5946b80a5507e..200fc7be605dd 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/events_table/events_table.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/settings/calendars/edit/events_table/events_table.tsx @@ -8,7 +8,7 @@ import type { FC } from 'react'; import React, { useCallback } from 'react'; import moment from 'moment-timezone'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiButton, EuiButtonEmpty, EuiIconTip, EuiInMemoryTable, EuiSpacer } from '@elastic/eui'; diff --git a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/timeseriesexplorer_controls/timeseriesexplorer_controls.tsx b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/timeseriesexplorer_controls/timeseriesexplorer_controls.tsx index c4663c64846ee..36e7b63094a29 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/timeseriesexplorer_controls/timeseriesexplorer_controls.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/timeseriesexplorer/components/timeseriesexplorer_controls/timeseriesexplorer_controls.tsx @@ -26,7 +26,7 @@ import { withSuspense, } from '@kbn/presentation-util-plugin/public'; import { useTimeRangeUpdates } from '@kbn/ml-date-picker'; -import type { MlJobState } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MlJobState } from '@elastic/elasticsearch/lib/api/types'; import { CASES_TOAST_MESSAGES_TITLES } from '../../../../cases/constants'; import type { CombinedJobWithStats } from '../../../../../server/shared'; import type { JobId } from '../../../../../common/types/anomaly_detection_jobs/job'; diff --git a/x-pack/platform/plugins/shared/ml/public/embeddables/common/process_filters.ts b/x-pack/platform/plugins/shared/ml/public/embeddables/common/process_filters.ts index e4b6079bfe0ea..a01b7562b27d4 100644 --- a/x-pack/platform/plugins/shared/ml/public/embeddables/common/process_filters.ts +++ b/x-pack/platform/plugins/shared/ml/public/embeddables/common/process_filters.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { AggregateQuery, Filter, Query } from '@kbn/es-query'; import { isOfAggregateQueryType } from '@kbn/es-query'; import { fromKueryExpression, luceneStringToDsl, toElasticsearchQuery } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx index 5d5193566bfbb..3bf418d2c9db3 100644 --- a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx +++ b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx @@ -23,7 +23,7 @@ import { import type { DataViewField, DataView } from '@kbn/data-views-plugin/common'; import type { TimeRange } from '@kbn/es-query'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { redirectToADJobWizards } from '../../../../application/jobs/new_job/job_from_pattern_analysis/utils'; import { createFieldOptions } from '../../../../application/jobs/new_job/common/job_creator/util/general'; import { NewJobCapsService } from '../../../../application/services/new_job_capabilities/new_job_capabilities_service'; diff --git a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/flyout.tsx b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/flyout.tsx index 240deec92053c..1ca9155bac17e 100644 --- a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/flyout.tsx +++ b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/flyout/flyout.tsx @@ -21,7 +21,7 @@ import { } from '@elastic/eui'; import type { DataViewField, DataView } from '@kbn/data-views-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { TimeRange } from '@kbn/es-query'; import { CreateJob } from './create_job'; diff --git a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/show_flyout.tsx b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/show_flyout.tsx index b461729254eaf..aee9deef41c3a 100644 --- a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/show_flyout.tsx +++ b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/aiops/show_flyout.tsx @@ -13,7 +13,7 @@ import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { LensPublicStart } from '@kbn/lens-plugin/public'; import type { DashboardStart } from '@kbn/dashboard-plugin/public'; import type { DataView, DataViewField } from '@kbn/data-views-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { TimeRange } from '@kbn/es-query'; import { createFlyout, type FlyoutComponentProps } from '../common/create_flyout'; import { CreateCategorizationJobFlyout } from './flyout'; diff --git a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/common/job_details.tsx b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/common/job_details.tsx index 0e843da22a74b..b853a2942fa30 100644 --- a/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/common/job_details.tsx +++ b/x-pack/platform/plugins/shared/ml/public/embeddables/job_creation/common/job_details.tsx @@ -9,7 +9,7 @@ import type { FC, PropsWithChildren } from 'react'; import React, { useState, useCallback } from 'react'; import useDebounce from 'react-use/lib/useDebounce'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiFlexGroup, EuiFlexItem, diff --git a/x-pack/platform/plugins/shared/ml/public/maps/anomaly_source_field.tsx b/x-pack/platform/plugins/shared/ml/public/maps/anomaly_source_field.tsx index fb984dfb82623..ea44202940dbb 100644 --- a/x-pack/platform/plugins/shared/ml/public/maps/anomaly_source_field.tsx +++ b/x-pack/platform/plugins/shared/ml/public/maps/anomaly_source_field.tsx @@ -12,7 +12,7 @@ import type { AggregationsExtendedStatsAggregation, AggregationsPercentilesAggregation, AggregationsTermsAggregation, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { escape } from 'lodash'; import { i18n } from '@kbn/i18n'; import type { Filter } from '@kbn/es-query'; diff --git a/x-pack/platform/plugins/shared/ml/public/maps/util.ts b/x-pack/platform/plugins/shared/ml/public/maps/util.ts index 1ea899fe5faae..85be61e5a0910 100644 --- a/x-pack/platform/plugins/shared/ml/public/maps/util.ts +++ b/x-pack/platform/plugins/shared/ml/public/maps/util.ts @@ -6,7 +6,7 @@ */ import type { FeatureCollection, Feature, Geometry } from 'geojson'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { htmlIdGenerator, type EuiThemeComputed } from '@elastic/eui'; import type { LayerDescriptor } from '@kbn/maps-plugin/common'; import { FIELD_ORIGIN, STYLE_TYPE } from '@kbn/maps-plugin/common'; @@ -199,7 +199,7 @@ export async function getResultsForJobId( } // Query to look for the highest scoring anomaly. - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { query: { bool, }, @@ -224,12 +224,7 @@ export async function getResultsForJobId( let resp: ESSearchResponse | null = null; try { - resp = await mlResultsService.anomalySearch( - { - body, - }, - [jobId] - ); + resp = await mlResultsService.anomalySearch(body, [jobId]); } catch (error) { // search may fail if the job doesn't already exist // ignore this error as the outer function call will raise a toast diff --git a/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.test.ts b/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.test.ts index 73010d5dcead4..1356cd6f55274 100644 --- a/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.test.ts +++ b/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.test.ts @@ -11,7 +11,7 @@ import type { DatafeedsService } from '../../models/job_service/datafeeds'; import type { Logger } from '@kbn/core/server'; import type { DeepPartial } from '@kbn/utility-types'; import type { MlClient } from '../ml_client'; -import type { MlJob, MlJobStats } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MlJob, MlJobStats } from '@elastic/elasticsearch/lib/api/types'; import type { AnnotationService } from '../../models/annotation_service/annotation'; import type { JobsHealthExecutorOptions } from './register_jobs_monitoring_rule_type'; import type { JobAuditMessagesService } from '../../models/job_audit_messages/job_audit_messages'; diff --git a/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.ts b/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.ts index 1e60dc1aeb3cf..0bc3199e1985b 100644 --- a/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.ts +++ b/x-pack/platform/plugins/shared/ml/server/lib/alerts/jobs_health_service.ts @@ -9,7 +9,7 @@ import { groupBy, keyBy, memoize, partition } from 'lodash'; import type { KibanaRequest, Logger, SavedObjectsClientContract } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; -import type { MlJob } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MlJob } from '@elastic/elasticsearch/lib/api/types'; import { isDefined } from '@kbn/ml-is-defined'; import { ALERT_REASON } from '@kbn/rule-data-utils'; import { parseInterval } from '@kbn/ml-parse-interval'; @@ -204,7 +204,7 @@ export function jobsHealthServiceProvider( // match datafeed stats with the job ids return (datafeedsStats as DatafeedStats[]) .map((datafeedStats) => { - const jobId = datafeedStats.timing_stats.job_id; + const jobId = datafeedStats.timing_stats!.job_id; const jobState = jobsStats.find((jobStats) => jobStats.job_id === jobId)?.state ?? 'failed'; return { diff --git a/x-pack/platform/plugins/shared/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts b/x-pack/platform/plugins/shared/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts index f499774945876..2f7a4e76c0665 100644 --- a/x-pack/platform/plugins/shared/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts +++ b/x-pack/platform/plugins/shared/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts @@ -14,7 +14,7 @@ import type { MlDatafeedState, MlJobState, MlJobStats, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { ActionGroup, AlertInstanceContext, diff --git a/x-pack/platform/plugins/shared/ml/server/lib/ml_client/ml_client.ts b/x-pack/platform/plugins/shared/ml/server/lib/ml_client/ml_client.ts index bbd5b7ef7d90f..e8f31e962de9d 100644 --- a/x-pack/platform/plugins/shared/ml/server/lib/ml_client/ml_client.ts +++ b/x-pack/platform/plugins/shared/ml/server/lib/ml_client/ml_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import type { DataFrameAnalyticsConfig } from '@kbn/ml-data-frame-analytics-utils'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; @@ -583,20 +583,9 @@ export function getMlClient( // but is added for type correctness below throw new Error('Incorrect arguments supplied'); } - // @ts-expect-error body doesn't exist in the type - const { model_id: id, body, query: querystring } = p[0]; return auditLogger.wrapTask( - () => - client.asInternalUser.transport.request( - { - method: 'POST', - path: `/_ml/trained_models/${id}/_infer`, - body, - querystring, - }, - p[1] - ), + () => client.asInternalUser.ml.inferTrainedModel(...p), 'ml_infer_trained_model', p ); @@ -776,7 +765,7 @@ export function getDatafeedIdsFromRequest([params]: MlGetDatafeedParams): string export function getJobIdFromBody(p: any): string | undefined { const [params] = p; - return params?.body?.job_id; + return params?.body?.job_id || params.job_id; } function filterAll(ids: string[]) { diff --git a/x-pack/platform/plugins/shared/ml/server/lib/ml_client/search.ts b/x-pack/platform/plugins/shared/ml/server/lib/ml_client/search.ts index b5899fab89dde..9a66ca8a5f4f5 100644 --- a/x-pack/platform/plugins/shared/ml/server/lib/ml_client/search.ts +++ b/x-pack/platform/plugins/shared/ml/server/lib/ml_client/search.ts @@ -7,7 +7,7 @@ import Boom from '@hapi/boom'; import type { IScopedClusterClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportResult, TransportRequestOptions, diff --git a/x-pack/platform/plugins/shared/ml/server/lib/ml_client/types.ts b/x-pack/platform/plugins/shared/ml/server/lib/ml_client/types.ts index d610baa92bc53..10f15bc2d192f 100644 --- a/x-pack/platform/plugins/shared/ml/server/lib/ml_client/types.ts +++ b/x-pack/platform/plugins/shared/ml/server/lib/ml_client/types.ts @@ -9,7 +9,7 @@ import type { TransportRequestOptionsWithMeta, TransportRequestOptions, } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { searchProvider } from './search'; diff --git a/x-pack/platform/plugins/shared/ml/server/models/annotation_service/__mocks__/get_annotations_request.json b/x-pack/platform/plugins/shared/ml/server/models/annotation_service/__mocks__/get_annotations_request.json index c65185a6172eb..7fdc1d441b05e 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/annotation_service/__mocks__/get_annotations_request.json +++ b/x-pack/platform/plugins/shared/ml/server/models/annotation_service/__mocks__/get_annotations_request.json @@ -2,85 +2,83 @@ "index": ".ml-annotations-read", "size": 500, "track_total_hits": true, - "body": { - "query": { - "bool": { - "filter": [ - { - "query_string": { - "query": "type:annotation", - "analyze_wildcard": false - } - }, - { - "bool": { - "must": [ - { - "bool": { - "must_not": [ - { - "bool": { - "filter": [ - { - "range": { - "timestamp": { - "lte": 1454804100000, - "format": "epoch_millis" - } + "query": { + "bool": { + "filter": [ + { + "query_string": { + "query": "type:annotation", + "analyze_wildcard": false + } + }, + { + "bool": { + "must": [ + { + "bool": { + "must_not": [ + { + "bool": { + "filter": [ + { + "range": { + "timestamp": { + "lte": 1454804100000, + "format": "epoch_millis" } - }, - { - "range": { - "end_timestamp": { - "lte": 1454804100000, - "format": "epoch_millis" - } + } + }, + { + "range": { + "end_timestamp": { + "lte": 1454804100000, + "format": "epoch_millis" } } - ] - } - }, - { - "bool": { - "filter": [ - { - "range": { - "timestamp": { - "gte": 1455233399999, - "format": "epoch_millis" - } + } + ] + } + }, + { + "bool": { + "filter": [ + { + "range": { + "timestamp": { + "gte": 1455233399999, + "format": "epoch_millis" } - }, - { - "range": { - "end_timestamp": { - "gte": 1455233399999, - "format": "epoch_millis" - } + } + }, + { + "range": { + "end_timestamp": { + "gte": 1455233399999, + "format": "epoch_millis" } } - ] - } + } + ] } - ] - } - }, - { - "exists": { - "field": "annotation" - } - }, - { - "query_string": { - "analyze_wildcard": false, - "query": "job_id:jobIdMock" - } + } + ] + } + }, + { + "exists": { + "field": "annotation" + } + }, + { + "query_string": { + "analyze_wildcard": false, + "query": "job_id:jobIdMock" } - ] - } + } + ] } - ] - } + } + ] } } } diff --git a/x-pack/platform/plugins/shared/ml/server/models/annotation_service/annotation.ts b/x-pack/platform/plugins/shared/ml/server/models/annotation_service/annotation.ts index 5446ad9f49ad7..a1b096e122a2a 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/annotation_service/annotation.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/annotation_service/annotation.ts @@ -9,7 +9,7 @@ import Boom from '@hapi/boom'; import { each, get } from 'lodash'; import type { IScopedClusterClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ML_PARTITION_FIELDS } from '@kbn/ml-anomaly-utils'; import { ANNOTATION_EVENT_USER, ANNOTATION_TYPE } from '../../../common/constants/annotations'; import { @@ -43,13 +43,6 @@ export interface IndexAnnotationArgs { event?: Annotation['event']; } -export interface GetParams { - index: string; - size: number; - body: object; - track_total_hits: boolean; -} - export interface GetResponse { success: true; annotations: Record; @@ -81,12 +74,10 @@ export function annotationProvider({ asInternalUser }: IScopedClusterClient) { async function fetchAnnotationIndex(id: string) { const searchParams: estypes.SearchRequest = { index: ML_ANNOTATIONS_INDEX_ALIAS_READ, - body: { - size: 1, - query: { - ids: { - values: [id], - }, + size: 1, + query: { + ids: { + values: [id], }, }, }; @@ -281,28 +272,26 @@ export function annotationProvider({ asInternalUser }: IScopedClusterClient) { ]; } - const params: GetParams = { + const params: estypes.SearchRequest = { index: ML_ANNOTATIONS_INDEX_ALIAS_READ, size: maxAnnotations, track_total_hits: true, - body: { - query: { - bool: { - filter: [ - { - query_string: { - query: `type:${ANNOTATION_TYPE.ANNOTATION}`, - analyze_wildcard: false, - }, + query: { + bool: { + filter: [ + { + query_string: { + query: `type:${ANNOTATION_TYPE.ANNOTATION}`, + analyze_wildcard: false, }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - ...(shouldClauses ? { should: shouldClauses, minimum_should_match: 1 } : {}), - }, + }, + ], + ...(shouldClauses ? { should: shouldClauses, minimum_should_match: 1 } : {}), }, }, }; @@ -365,34 +354,32 @@ export function annotationProvider({ asInternalUser }: IScopedClusterClient) { }): Promise { const params: estypes.SearchRequest = { index: ML_ANNOTATIONS_INDEX_ALIAS_READ, - body: { - size: 0, - query: { - bool: { - filter: [ - ...(earliestMs ? [{ range: { end_timestamp: { gte: earliestMs } } }] : []), - { - term: { event: { value: 'delayed_data' } }, - }, - { terms: { job_id: jobIds } }, - ], - }, + size: 0, + query: { + bool: { + filter: [ + ...(earliestMs ? [{ range: { end_timestamp: { gte: earliestMs } } }] : []), + { + term: { event: { value: 'delayed_data' } }, + }, + { terms: { job_id: jobIds } }, + ], }, - aggs: { - by_job: { - terms: { field: 'job_id', size: jobIds.length }, - aggs: { - latest_delayed: { - top_hits: { - size: 1, - sort: [ - { - end_timestamp: { - order: 'desc', - }, + }, + aggs: { + by_job: { + terms: { field: 'job_id', size: jobIds.length }, + aggs: { + latest_delayed: { + top_hits: { + size: 1, + sort: [ + { + end_timestamp: { + order: 'desc', }, - ], - }, + }, + ], }, }, }, diff --git a/x-pack/platform/plugins/shared/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts b/x-pack/platform/plugins/shared/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts index c36e569a6eb3a..f3f86ee1593c7 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import numeral from '@elastic/numeral'; import type { IScopedClusterClient } from '@kbn/core/server'; import { MLCATEGORY } from '@kbn/ml-anomaly-utils'; @@ -153,9 +153,12 @@ export function calculateModelMemoryLimitProvider( datafeedConfig?: Datafeed ): Promise { const info = await mlClient.info(); - const maxModelMemoryLimit = info.limits.max_model_memory_limit?.toUpperCase(); - const effectiveMaxModelMemoryLimit = - info.limits.effective_max_model_memory_limit?.toUpperCase(); + const maxModelMemoryLimit = ( + info.limits.max_model_memory_limit as string | undefined + )?.toUpperCase(); + const effectiveMaxModelMemoryLimit = ( + info.limits.effective_max_model_memory_limit as string | undefined + )?.toUpperCase(); const { overallCardinality, maxBucketCardinality } = await getCardinalities( analysisConfig, @@ -168,11 +171,9 @@ export function calculateModelMemoryLimitProvider( ); const body = await mlClient.estimateModelMemory({ - body: { - analysis_config: analysisConfig, - overall_cardinality: overallCardinality, - max_bucket_cardinality: maxBucketCardinality, - }, + analysis_config: analysisConfig, + overall_cardinality: overallCardinality, + max_bucket_cardinality: maxBucketCardinality, }); const estimatedModelMemoryLimit = body.model_memory_estimate.toUpperCase(); diff --git a/x-pack/platform/plugins/shared/ml/server/models/calendar/calendar_manager.ts b/x-pack/platform/plugins/shared/ml/server/models/calendar/calendar_manager.ts index 37b76013d6808..9098fc5aa292d 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/calendar/calendar_manager.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/calendar/calendar_manager.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { difference } from 'lodash'; import { EventManager } from './event_manager'; import type { MlClient } from '../../lib/ml_client'; @@ -47,7 +47,7 @@ export class CalendarManager { } async getAllCalendars() { - const body = await this._mlClient.getCalendars({ body: { page: { from: 0, size: 10000 } } }); + const body = await this._mlClient.getCalendars({ page: { from: 0, size: 10000 } }); const events: ScheduledEvent[] = await this._eventManager.getAllEvents(); const calendars: Calendar[] = body.calendars as Calendar[]; @@ -77,7 +77,7 @@ export class CalendarManager { const { calendarId, events, ...newCalendar } = calendar; await this._mlClient.putCalendar({ calendar_id: calendarId, - body: newCalendar, + ...newCalendar, }); if (events.length) { diff --git a/x-pack/platform/plugins/shared/ml/server/models/calendar/event_manager.ts b/x-pack/platform/plugins/shared/ml/server/models/calendar/event_manager.ts index 8aa48a05fdc31..77862c3a76b85 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/calendar/event_manager.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/calendar/event_manager.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { GLOBAL_CALENDAR } from '../../../common/constants/calendars'; import type { MlClient } from '../../lib/ml_client'; @@ -35,11 +35,9 @@ export class EventManager { } async addEvents(calendarId: string, events: ScheduledEvent[]) { - const body = { events }; - return await this._mlClient.postCalendarEvents({ calendar_id: calendarId, - body, + events, }); } diff --git a/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_audit_messages.ts b/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_audit_messages.ts index 73c6260c6e286..d498d2b124621 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_audit_messages.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_audit_messages.ts @@ -74,10 +74,8 @@ export function analyticsAuditMessagesProvider({ asInternalUser }: IScopedCluste index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, size: SIZE, - body: { - sort: [{ timestamp: { order: 'desc' } }, { job_id: { order: 'asc' } }], - query, - }, + sort: [{ timestamp: { order: 'desc' } }, { job_id: { order: 'asc' } }], + query, }, { maxRetries: 0 } ); diff --git a/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_manager.ts b/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_manager.ts index 04a14c7f235ff..e6bf57ef81a7b 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_manager.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/analytics_manager.ts @@ -6,7 +6,7 @@ */ import Boom from '@hapi/boom'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import { getAnalysisType, diff --git a/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/validation.ts b/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/validation.ts index 515de87e79c56..dd192d1d4509d 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/validation.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/data_frame_analytics/validation.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import { extractErrorMessage } from '@kbn/ml-error-utils'; import { @@ -264,11 +264,9 @@ async function getValidationCheckMessages( index, size: 0, track_total_hits: true, - body: { - ...(source.runtime_mappings ? { runtime_mappings: source.runtime_mappings } : {}), - query, - aggs, - }, + ...(source.runtime_mappings ? { runtime_mappings: source.runtime_mappings } : {}), + query, + aggs, }, { maxRetries: 0 } ); diff --git a/x-pack/platform/plugins/shared/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/platform/plugins/shared/ml/server/models/data_recognizer/data_recognizer.ts index 41a8f60f912f3..c27655a4211f1 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/data_recognizer/data_recognizer.ts @@ -886,7 +886,7 @@ export class DataRecognizer { } private async _saveJob(job: ModuleJob) { - return this._mlClient.putJob({ job_id: job.id, body: job.config }); + return this._mlClient.putJob({ job_id: job.id, ...job.config }); } // save the datafeeds. @@ -920,7 +920,7 @@ export class DataRecognizer { return this._mlClient.putDatafeed( { datafeed_id: datafeed.id, - body: datafeed.config, + ...datafeed.config, }, this._authorizationHeader ); diff --git a/x-pack/platform/plugins/shared/ml/server/models/data_visualizer/data_visualizer.ts b/x-pack/platform/plugins/shared/ml/server/models/data_visualizer/data_visualizer.ts index fa84a271e84bd..0e104d18d75d9 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/data_visualizer/data_visualizer.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/data_visualizer/data_visualizer.ts @@ -438,7 +438,7 @@ export class DataVisualizer { index, track_total_hits: true, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -531,7 +531,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -579,7 +579,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -674,7 +674,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -787,7 +787,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -866,7 +866,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -938,7 +938,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); @@ -1006,7 +1006,7 @@ export class DataVisualizer { { index, size, - body: searchBody, + ...searchBody, }, { maxRetries: 0 } ); diff --git a/x-pack/platform/plugins/shared/ml/server/models/fields_service/fields_service.ts b/x-pack/platform/plugins/shared/ml/server/models/fields_service/fields_service.ts index f68a7b0c7560d..9435f7609a2b6 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/fields_service/fields_service.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/fields_service/fields_service.ts @@ -8,7 +8,7 @@ import Boom from '@hapi/boom'; import { duration } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import type { AggCardinality } from '@kbn/ml-agg-utils'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; @@ -242,22 +242,20 @@ export function fieldsServiceProvider({ asCurrentUser }: IScopedClusterClient) { { index, size: 0, - body: { - ...(query ? { query } : {}), - aggs: { - earliest: { - min: { - field: timeFieldName, - }, + ...(query ? { query } : {}), + aggs: { + earliest: { + min: { + field: timeFieldName, }, - latest: { - max: { - field: timeFieldName, - }, + }, + latest: { + max: { + field: timeFieldName, }, }, - ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), }, + ...(isPopulatedObject(runtimeMappings) ? { runtime_mappings: runtimeMappings } : {}), ...(indicesOptions ?? {}), }, { maxRetries: 0 } @@ -417,7 +415,7 @@ export function fieldsServiceProvider({ asCurrentUser }: IScopedClusterClient) { const { aggregations } = await asCurrentUser.search( { index, - body, + ...body, ...getIndicesOptions(datafeedConfig), }, { maxRetries: 0 } diff --git a/x-pack/platform/plugins/shared/ml/server/models/filter/filter_manager.ts b/x-pack/platform/plugins/shared/ml/server/models/filter/filter_manager.ts index 3aed4b80a792d..e905cc1ab67fe 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/filter/filter_manager.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/filter/filter_manager.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import Boom from '@hapi/boom'; import type { MlClient } from '../../lib/ml_client'; @@ -107,7 +107,7 @@ export class FilterManager { const { filterId, ...body } = filter; // Returns the newly created filter. - return await this._mlClient.putFilter({ filter_id: filterId, body }); + return await this._mlClient.putFilter({ filter_id: filterId, ...body }); } async updateFilter(filterId: string, filter: UpdateFilter) { @@ -123,10 +123,7 @@ export class FilterManager { } // Returns the newly updated filter. - const resp = await this._mlClient.updateFilter({ - filter_id: filterId, - body, - }); + const resp = await this._mlClient.updateFilter(body); return resp; } diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_audit_messages/job_audit_messages.ts b/x-pack/platform/plugins/shared/ml/server/models/job_audit_messages/job_audit_messages.ts index 52f2f9b0cadae..fdddd71954a58 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_audit_messages/job_audit_messages.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_audit_messages/job_audit_messages.ts @@ -7,8 +7,8 @@ import moment from 'moment'; import type { IScopedClusterClient } from '@kbn/core/server'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ML_NOTIFICATION_INDEX_PATTERN } from '../../../common/constants/index_patterns'; import { MESSAGE_LEVEL } from '../../../common/constants/message_levels'; import type { MLSavedObjectService } from '../../saved_objects'; @@ -155,10 +155,8 @@ export function jobAuditMessagesProvider( index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, size: SIZE, - body: { - sort: [{ timestamp: { order: 'desc' } }, { job_id: { order: 'asc' } }], - query, - }, + sort: [{ timestamp: { order: 'desc' } }, { job_id: { order: 'asc' } }], + query, }, { maxRetries: 0 } ); @@ -230,33 +228,31 @@ export function jobAuditMessagesProvider( index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, size: 0, - body: { - query, - aggs: { - levelsPerJob: { - terms: { - field: 'job_id', - size: levelsPerJobAggSize, - }, - aggs: { - levels: { - terms: { - field: 'level', - }, - aggs: { - latestMessage: { - terms: { - field: 'message.raw', - size: 1, - order: { - latestMessage: 'desc', - }, + query, + aggs: { + levelsPerJob: { + terms: { + field: 'job_id', + size: levelsPerJobAggSize, + }, + aggs: { + levels: { + terms: { + field: 'level', + }, + aggs: { + latestMessage: { + terms: { + field: 'message.raw', + size: 1, + order: { + latestMessage: 'desc', }, - aggs: { - latestMessage: { - max: { - field: 'timestamp', - }, + }, + aggs: { + latestMessage: { + max: { + field: 'timestamp', }, }, }, @@ -401,12 +397,10 @@ export function jobAuditMessagesProvider( ignore_unavailable: true, refresh: false, conflicts: 'proceed', - body: { - query, - script: { - source: 'ctx._source.cleared = true', - lang: 'painless', - }, + query, + script: { + source: 'ctx._source.cleared = true', + lang: 'painless', }, }, { maxRetries: 0 } @@ -445,36 +439,34 @@ export function jobAuditMessagesProvider( index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, size: 0, - body: { - query: { - bool: { - filter: [ - ...(earliestMs ? [{ range: { timestamp: { gte: earliestMs } } }] : []), - { terms: { job_id: jobIds } }, - { - term: { level: { value: MESSAGE_LEVEL.ERROR } }, - }, - ], - }, - }, - aggs: { - by_job: { - terms: { - field: 'job_id', - size: jobIds.length, + query: { + bool: { + filter: [ + ...(earliestMs ? [{ range: { timestamp: { gte: earliestMs } } }] : []), + { terms: { job_id: jobIds } }, + { + term: { level: { value: MESSAGE_LEVEL.ERROR } }, }, - aggs: { - latest_errors: { - top_hits: { - size: 10, - sort: [ - { - timestamp: { - order: 'desc', - }, + ], + }, + }, + aggs: { + by_job: { + terms: { + field: 'job_id', + size: jobIds.length, + }, + aggs: { + latest_errors: { + top_hits: { + size: 10, + sort: [ + { + timestamp: { + order: 'desc', }, - ], - }, + }, + ], }, }, }, diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/datafeeds.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/datafeeds.ts index 5c2c44c326c8c..906e78a4e097f 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/datafeeds.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/datafeeds.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import type { IScopedClusterClient } from '@kbn/core/server'; import { JOB_STATE, DATAFEED_STATE } from '../../../common/constants/states'; @@ -106,10 +106,8 @@ export function datafeedsProvider(client: IScopedClusterClient, mlClient: MlClie async function startDatafeed(datafeedId: string, start?: number, end?: number) { return mlClient.startDatafeed({ datafeed_id: datafeedId, - body: { - start: start !== undefined ? String(start) : undefined, - end: end !== undefined ? String(end) : undefined, - }, + start: start !== undefined ? String(start) : undefined, + end: end !== undefined ? String(end) : undefined, }); } diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/groups.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/groups.ts index 06641fff9795f..b4975d281134c 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/groups.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/groups.ts @@ -74,7 +74,7 @@ export function groupsProvider(mlClient: MlClient) { for (const job of jobs) { const { jobId, groups } = job; try { - await mlClient.updateJob({ job_id: jobId, body: { groups } }); + await mlClient.updateJob({ job_id: jobId, groups }); results[jobId] = { success: true }; } catch ({ body }) { results[jobId] = { success: false, error: body }; diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/jobs.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/jobs.ts index fa779258e5f23..06d8bcaeb0467 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/jobs.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/jobs.ts @@ -218,7 +218,7 @@ export function jobsProvider( const body = await mlClient.stopDatafeed({ datafeed_id: datafeedId, - body: { force: true }, + force: true, }); if (body.stopped !== true) { return { success: false }; @@ -682,17 +682,14 @@ export function jobsProvider( results[job.job_id] = { job: { success: false }, datafeed: { success: false } }; try { - await mlClient.putJob({ job_id: job.job_id, body: job }); + await mlClient.putJob(job); results[job.job_id].job = { success: true }; } catch (error) { results[job.job_id].job = { success: false, error: error.body ?? error }; } try { - await mlClient.putDatafeed( - { datafeed_id: datafeed.datafeed_id, body: datafeed }, - authHeader - ); + await mlClient.putDatafeed(datafeed, authHeader); results[job.job_id].datafeed = { success: true }; } catch (error) { results[job.job_id].datafeed = { success: false, error: error.body ?? error }; diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/model_snapshots.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/model_snapshots.ts index b72ad7d1a4fed..49699ee755567 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/model_snapshots.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/model_snapshots.ts @@ -64,9 +64,7 @@ export function modelSnapshotProvider(client: IScopedClusterClient, mlClient: Ml const { model } = await mlClient.revertModelSnapshot({ job_id: jobId, snapshot_id: snapshotId, - body: { - delete_intervening_results: deleteInterveningResults, - }, + delete_intervening_results: deleteInterveningResults, }); // create calendar (if specified) and replay datafeed diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job/categorization/top_categories.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job/categorization/top_categories.ts index 339ba87fc423b..5990363b919c2 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job/categorization/top_categories.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job/categorization/top_categories.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { CategoryId, Category } from '../../../../../common/types/categories'; import type { MlClient } from '../../../../lib/ml_client'; @@ -14,23 +14,21 @@ export function topCategoriesProvider(mlClient: MlClient) { async function getTotalCategories(jobId: string): Promise { const body = await mlClient.anomalySearch>( { - body: { - size: 0, - query: { - bool: { - filter: [ - { - term: { - job_id: jobId, - }, + size: 0, + query: { + bool: { + filter: [ + { + term: { + job_id: jobId, }, - { - exists: { - field: 'category_id', - }, + }, + { + exists: { + field: 'category_id', }, - ], - }, + }, + ], }, }, }, @@ -42,35 +40,33 @@ export function topCategoriesProvider(mlClient: MlClient) { async function getTopCategoryCounts(jobId: string, numberOfCategories: number) { const body = await mlClient.anomalySearch>( { - body: { - size: 0, - query: { - bool: { - filter: [ - { - term: { - job_id: jobId, - }, + size: 0, + query: { + bool: { + filter: [ + { + term: { + job_id: jobId, }, - { - term: { - result_type: 'model_plot', - }, + }, + { + term: { + result_type: 'model_plot', }, - { - term: { - by_field_name: 'mlcategory', - }, + }, + { + term: { + by_field_name: 'mlcategory', }, - ], - }, - }, - aggs: { - cat_count: { - terms: { - field: 'by_field_value', - size: numberOfCategories, }, + ], + }, + }, + aggs: { + cat_count: { + terms: { + field: 'by_field_value', + size: numberOfCategories, }, }, }, @@ -107,19 +103,17 @@ export function topCategoriesProvider(mlClient: MlClient) { }; const body = await mlClient.anomalySearch( { - body: { - size, - query: { - bool: { - filter: [ - { - term: { - job_id: jobId, - }, + size, + query: { + bool: { + filter: [ + { + term: { + job_id: jobId, }, - categoryFilter, - ], - }, + }, + categoryFilter, + ], }, }, }, diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/field_service.ts index 74065222a529d..2fd88f254ea9c 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/field_service.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/field_service.ts @@ -6,7 +6,7 @@ */ import { cloneDeep } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import { ES_FIELD_TYPES } from '@kbn/field-types'; import type { DataViewsService } from '@kbn/data-views-plugin/common'; diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/rollup.ts index 0bddc3b2dff21..880dc3f18013b 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/rollup.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_service/new_job_caps/rollup.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import type { DataViewsService, DataView } from '@kbn/data-views-plugin/common'; import type { RollupFields } from '@kbn/ml-anomaly-utils'; diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_datafeed_preview.ts b/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_datafeed_preview.ts index 4477f423da25d..c17e6018b1ed9 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_datafeed_preview.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_datafeed_preview.ts @@ -42,10 +42,8 @@ export async function validateDatafeedPreview( try { const body = (await mlClient.previewDatafeed( { - body: { - job_config: tempJob, - datafeed_config: datafeed, - }, + job_config: tempJob, + datafeed_config: datafeed, start, end, }, diff --git a/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_model_memory_limit.ts b/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_model_memory_limit.ts index 85ce1cd8d3427..a39c9c6fe2842 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_model_memory_limit.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/job_validation/validate_model_memory_limit.ts @@ -29,7 +29,8 @@ export async function validateModelMemoryLimit( // retrieve the model memory limit specified by the user in the job config. // note, this will probably be the auto generated value, unless the user has // over written it. - const mml = job?.analysis_limits?.model_memory_limit?.toUpperCase() ?? null; + const mml = + (job?.analysis_limits?.model_memory_limit as string | undefined)?.toUpperCase() ?? null; const messages = []; @@ -56,8 +57,12 @@ export async function validateModelMemoryLimit( // retrieve the max_model_memory_limit value from the server // this will be unset unless the user has set this on their cluster const body = await mlClient.info(); - const maxModelMemoryLimit = body.limits.max_model_memory_limit?.toUpperCase(); - const effectiveMaxModelMemoryLimit = body.limits.effective_max_model_memory_limit?.toUpperCase(); + const maxModelMemoryLimit = ( + body.limits.max_model_memory_limit as string | undefined + )?.toUpperCase(); + const effectiveMaxModelMemoryLimit = ( + body.limits.effective_max_model_memory_limit as string | undefined + )?.toUpperCase(); if (runCalcModelMemoryTest) { const { modelMemoryLimit } = await calculateModelMemoryLimitProvider(client, mlClient)( diff --git a/x-pack/platform/plugins/shared/ml/server/models/model_management/memory_usage.ts b/x-pack/platform/plugins/shared/ml/server/models/model_management/memory_usage.ts index 6e9121a133bb8..05d40f53087a8 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/model_management/memory_usage.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/model_management/memory_usage.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import numeral from '@elastic/numeral'; import { pick } from 'lodash'; import { isDefined } from '@kbn/ml-is-defined'; @@ -164,7 +164,7 @@ export class MemoryUsageService { id: trainedModelStats.model_id, type: 'trained-model', size, - nodeNames: nodes.map((n) => Object.values(n.node)[0].name), + nodeNames: nodes.map((n) => Object.values(n.node || {})[0]?.name!), }; } @@ -193,7 +193,7 @@ export class MemoryUsageService { (d) => isDefined(d.deployment_stats) && isDefined(d.deployment_stats.nodes) && - d.deployment_stats.nodes.some((n) => Object.keys(n.node)[0] === nodeId) + d.deployment_stats.nodes.some((n) => Object.keys(n.node || {})[0] === nodeId) ) .map((d) => { const modelSizeState = d.model_size_stats; @@ -206,7 +206,7 @@ export class MemoryUsageService { const { nodes, ...rest } = deploymentStats; const { node: tempNode, ...nodeRest } = nodes.find( - (v) => Object.keys(v.node)[0] === nodeId + (v) => Object.keys(v.node || {})[0] === nodeId )!; return { model_id: d.model_id, diff --git a/x-pack/platform/plugins/shared/ml/server/models/model_management/model_provider.test.ts b/x-pack/platform/plugins/shared/ml/server/models/model_management/model_provider.test.ts index 53cc37d33cdc3..861c312e9fd7e 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/model_management/model_provider.test.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/model_management/model_provider.test.ts @@ -14,7 +14,7 @@ import { mlLog } from '../../lib/log'; import { errors } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import type { ExistingModelBase } from '../../../common/types/trained_models'; -import type { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { InferenceInferenceEndpointInfo } from '@elastic/elasticsearch/lib/api/types'; jest.mock('../../lib/log'); diff --git a/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts b/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts index 9f45b8483bf21..0a2293bd713ac 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts @@ -12,6 +12,7 @@ import { flatten, groupBy, isEmpty } from 'lodash'; import type { InferenceInferenceEndpoint, InferenceTaskType, + IngestDocument, MlGetTrainedModelsRequest, TasksTaskInfo, TransformGetTransformTransformSummary, @@ -19,7 +20,6 @@ import type { import type { IndexName, IndicesIndexState } from '@elastic/elasticsearch/lib/api/types'; import type { IngestPipeline, - IngestSimulateDocument, IngestSimulateRequest, NodesInfoResponseBase, } from '@elastic/elasticsearch/lib/api/types'; @@ -432,7 +432,7 @@ export class ModelsProvider { * Simulates the effect of the pipeline on given document. * */ - async simulatePipeline(docs: IngestSimulateDocument[], pipelineConfig: IngestPipeline) { + async simulatePipeline(docs: IngestDocument[], pipelineConfig: IngestPipeline) { const simulateRequest: IngestSimulateRequest = { docs, pipeline: pipelineConfig, diff --git a/x-pack/platform/plugins/shared/ml/server/models/notifications_service/notifications_service_provider.ts b/x-pack/platform/plugins/shared/ml/server/models/notifications_service/notifications_service_provider.ts index 5b6239d034527..8dc8c74516a3f 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/notifications_service/notifications_service_provider.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/notifications_service/notifications_service_provider.ts @@ -6,7 +6,7 @@ */ import type { IScopedClusterClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { MlFeatures } from '../../../common/constants/app'; import type { MLSavedObjectService } from '../../saved_objects'; import type { NotificationItem, NotificationSource } from '../../../common/types/notifications'; @@ -89,53 +89,51 @@ export class NotificationsService { ignore_unavailable: true, from: 0, size: MAX_NOTIFICATIONS_SIZE, - body: { - sort: [{ [params.sortField]: { order: params.sortDirection } }], - query: { - bool: { - ...(params.queryString - ? { - must: [ - { - query_string: { - query: params.queryString, - default_field: 'message', - }, + sort: [{ [params.sortField]: { order: params.sortDirection } }], + query: { + bool: { + ...(params.queryString + ? { + must: [ + { + query_string: { + query: params.queryString, + default_field: 'message', }, - ], - } - : {}), - filter: [ - ...(v.ids - ? [ - { - terms: { - job_id: v.ids as string[], - }, + }, + ], + } + : {}), + filter: [ + ...(v.ids + ? [ + { + terms: { + job_id: v.ids as string[], }, - ] - : []), - { - term: { - job_type: { - value: v.type, }, + ] + : []), + { + term: { + job_type: { + value: v.type, }, }, - ...(params.earliest || params.latest - ? [ - { - range: { - timestamp: { - ...(params.earliest ? { gt: params.earliest } : {}), - ...(params.latest ? { lte: params.latest } : {}), - }, + }, + ...(params.earliest || params.latest + ? [ + { + range: { + timestamp: { + ...(params.earliest ? { gt: params.earliest } : {}), + ...(params.latest ? { lte: params.latest } : {}), }, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, }, }, @@ -217,40 +215,38 @@ export class NotificationsService { const responseBody = await this.scopedClusterClient.asInternalUser.search({ size: 0, index: ML_NOTIFICATION_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - ...(v.ids - ? [ - { - terms: { - job_id: v.ids as string[], - }, + query: { + bool: { + filter: [ + ...(v.ids + ? [ + { + terms: { + job_id: v.ids as string[], }, - ] - : []), - { - term: { - job_type: { - value: v.type, }, + ] + : []), + { + term: { + job_type: { + value: v.type, }, }, - { - range: { - timestamp: { - gt: params.lastCheckedAt, - }, + }, + { + range: { + timestamp: { + gt: params.lastCheckedAt, }, }, - ], - }, + }, + ], }, - aggs: { - by_level: { - terms: { field: 'level' }, - }, + }, + aggs: { + by_level: { + terms: { field: 'level' }, }, }, }); diff --git a/x-pack/platform/plugins/shared/ml/server/models/results_service/anomaly_charts.ts b/x-pack/platform/plugins/shared/ml/server/models/results_service/anomaly_charts.ts index 2220cf86d3edb..f2bd9f960e3de 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/results_service/anomaly_charts.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/results_service/anomaly_charts.ts @@ -8,7 +8,7 @@ import type { IScopedClusterClient } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; import { each, find, get, keyBy, map, reduce, sortBy } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { extent, max, min } from 'd3'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { isDefined } from '@kbn/ml-is-defined'; @@ -1928,26 +1928,24 @@ export function anomalyChartsDataProvider(mlClient: MlClient, client: IScopedClu const response = await mlClient.anomalySearch>( { - body: { - size: maxResults !== undefined ? maxResults : 100, - query: { - bool: { - filter: [ - { - term: { - result_type: 'record', - }, + size: maxResults !== undefined ? maxResults : 100, + query: { + bool: { + filter: [ + { + term: { + result_type: 'record', }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - }, + }, + ], }, - sort: [{ record_score: { order: 'desc' } }], }, + sort: [{ record_score: { order: 'desc' } }], }, jobIds ); diff --git a/x-pack/platform/plugins/shared/ml/server/models/results_service/get_partition_fields_values.ts b/x-pack/platform/plugins/shared/ml/server/models/results_service/get_partition_fields_values.ts index 5e7d01b4bf9fb..0342008eda946 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/results_service/get_partition_fields_values.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/results_service/get_partition_fields_values.ts @@ -6,7 +6,7 @@ */ import Boom from '@hapi/boom'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { type MlPartitionFieldsType, ML_PARTITION_FIELDS } from '@kbn/ml-anomaly-utils'; import type { CriteriaField } from './results_service'; import type { FieldConfig, FieldsConfig } from '../../routes/schemas/results_service_schema'; @@ -205,7 +205,7 @@ export const getPartitionFieldsValuesFactory = (mlClient: MlClient) => // it includes the records that occurred as anomalies historically const searchAllTime = !isModelPlotEnabled && !applyTimeRange; - const requestBody: estypes.SearchRequest['body'] = { + const requestBody: estypes.SearchRequest = { query: { bool: { filter: [ @@ -254,10 +254,8 @@ export const getPartitionFieldsValuesFactory = (mlClient: MlClient) => const body = await mlClient.anomalySearch( { - body: { - ...requestBody, - size: 0, - }, + ...requestBody, + size: 0, }, [jobId] ); diff --git a/x-pack/platform/plugins/shared/ml/server/models/results_service/results_service.ts b/x-pack/platform/plugins/shared/ml/server/models/results_service/results_service.ts index a0a11bfcc912c..ed4307cc0a664 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/results_service/results_service.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/results_service/results_service.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { sortBy, slice, get, cloneDeep } from 'lodash'; import moment from 'moment'; import Boom from '@hapi/boom'; @@ -196,27 +196,25 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust const body = await mlClient.anomalySearch( { - body: { - size: maxRecords, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:record', - analyze_wildcard: false, - }, + size: maxRecords, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:record', + analyze_wildcard: false, }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - }, + }, + ], }, - sort: [{ record_score: { order: 'desc' } }], }, + sort: [{ record_score: { order: 'desc' } }], }, jobIds ); @@ -321,29 +319,27 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust const query = { size: 0, - body: { - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:bucket', - analyze_wildcard: false, - }, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:bucket', + analyze_wildcard: false, }, - { - bool: { - must: boolCriteria, - }, + }, + { + bool: { + must: boolCriteria, }, - ], - }, - }, - aggs: { - max_score: { - max: { - field: 'anomaly_score', }, + ], + }, + }, + aggs: { + max_score: { + max: { + field: 'anomaly_score', }, }, }, @@ -389,24 +385,22 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust const body = await mlClient.anomalySearch( { - body: { - size: 0, - query: { - bool: { - filter, - }, + size: 0, + query: { + bool: { + filter, }, - aggs: { - byJobId: { - terms: { - field: 'job_id', - size: maxJobs, - }, - aggs: { - maxTimestamp: { - max: { - field: 'timestamp', - }, + }, + aggs: { + byJobId: { + terms: { + field: 'job_id', + size: maxJobs, + }, + aggs: { + maxTimestamp: { + max: { + field: 'timestamp', }, }, }, @@ -435,12 +429,10 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust async function getCategoryExamples(jobId: string, categoryIds: any, maxExamples: number) { const body = await mlClient.anomalySearch( { - body: { - size: ANOMALIES_TABLE_DEFAULT_QUERY_SIZE, // Matches size of records in anomaly summary table. - query: { - bool: { - filter: [{ term: { job_id: jobId } }, { terms: { category_id: categoryIds } }], - }, + size: ANOMALIES_TABLE_DEFAULT_QUERY_SIZE, // Matches size of records in anomaly summary table. + query: { + bool: { + filter: [{ term: { job_id: jobId } }, { terms: { category_id: categoryIds } }], }, }, }, @@ -472,12 +464,10 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust async function getCategoryDefinition(jobId: string, categoryId: string) { const body = await mlClient.anomalySearch( { - body: { - size: 1, - query: { - bool: { - filter: [{ term: { job_id: jobId } }, { term: { category_id: categoryId } }], - }, + size: 1, + query: { + bool: { + filter: [{ term: { job_id: jobId } }, { term: { category_id: categoryId } }], }, }, }, @@ -515,18 +505,16 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust } const body = await mlClient.anomalySearch( { - body: { - query: { - bool: { - must: mustMatchClauses, - filter: [ - { - term: { - job_id: jobId, - }, + query: { + bool: { + must: mustMatchClauses, + filter: [ + { + term: { + job_id: jobId, }, - ], - }, + }, + ], }, }, }, @@ -604,22 +592,20 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust ]; const results = await mlClient.anomalySearch( { - body: { - size: 0, - query: { - bool: { - must: mustMatchClauses, - filter: [ - { - terms: { - job_id: jobIdsWithStopOnWarnSet, - }, + size: 0, + query: { + bool: { + must: mustMatchClauses, + filter: [ + { + terms: { + job_id: jobIdsWithStopOnWarnSet, }, - ], - }, + }, + ], }, - aggs, }, + aggs, }, jobIds ); @@ -713,21 +699,19 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust const esSearchRequest = { index: datafeedConfig.indices.join(','), - body: { - query: datafeedQueryClone, - ...(datafeedConfig.runtime_mappings - ? { runtime_mappings: datafeedConfig.runtime_mappings } - : {}), - aggs: { - doc_count_by_bucket_span: { - date_histogram: { - field: timefield, - fixed_interval: bucketSpan, - }, + query: datafeedQueryClone, + ...(datafeedConfig.runtime_mappings + ? { runtime_mappings: datafeedConfig.runtime_mappings } + : {}), + aggs: { + doc_count_by_bucket_span: { + date_histogram: { + field: timefield, + fixed_interval: bucketSpan, }, }, - size: 0, }, + size: 0, ...getIndicesOptions(datafeedConfig), }; @@ -749,7 +733,10 @@ export function resultsServiceProvider(mlClient: MlClient, client?: IScopedClust const [bucketResp, annotationResp] = await Promise.all([ mlClient.getBuckets({ job_id: jobId, - body: { desc: true, start: String(start), end: String(end), page: { from: 0, size: 1000 } }, + desc: true, + start: String(start), + end: String(end), + page: { from: 0, size: 1000 }, }), getAnnotations({ jobIds: [jobId], diff --git a/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts b/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts index f9bd3f6661e4a..13595339308e6 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; @@ -479,7 +479,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { const body = await mlClient.getBuckets({ job_id: request.params.jobId, timestamp: request.params.timestamp, - body: request.body, + ...request.body, }); return response.ok({ body, @@ -666,7 +666,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { const body = await mlClient.updateModelSnapshot({ job_id: request.params.jobId, snapshot_id: request.params.snapshotId, - body: request.body, + ...request.body, }); return response.ok({ body, diff --git a/x-pack/platform/plugins/shared/ml/server/routes/data_frame_analytics.ts b/x-pack/platform/plugins/shared/ml/server/routes/data_frame_analytics.ts index 007361f97af4a..2d22b664f15ea 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/data_frame_analytics.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/data_frame_analytics.ts @@ -102,14 +102,12 @@ export function dataFrameAnalyticsRoutes( } const body = await client.asCurrentUser.security.hasPrivileges({ - body: { - index: [ - { - names: [destinationIndex], // uses wildcard - privileges: ['delete_index'], - }, - ], - }, + index: [ + { + names: [destinationIndex], // uses wildcard + privileges: ['delete_index'], + }, + ], }); return body?.has_all_requested === true; @@ -400,6 +398,7 @@ export function dataFrameAnalyticsRoutes( try { const body = await mlClient.explainDataFrameAnalytics( { + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 (_meta) body: request.body, }, getAuthorizationHeader(request) @@ -620,6 +619,7 @@ export function dataFrameAnalyticsRoutes( const body = await mlClient.updateDataFrameAnalytics( { id: analyticsId, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 (_meta) body: request.body, }, getAuthorizationHeader(request) diff --git a/x-pack/platform/plugins/shared/ml/server/routes/datafeeds.ts b/x-pack/platform/plugins/shared/ml/server/routes/datafeeds.ts index 8939471ef5624..01a402a2f6586 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/datafeeds.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/datafeeds.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; import type { RouteInitialization } from '../types'; @@ -309,10 +309,8 @@ export function dataFeedRoutes({ router, routeGuard }: RouteInitialization) { const body = await mlClient.startDatafeed({ datafeed_id: datafeedId, - body: { - start: start !== undefined ? String(start) : undefined, - end: end !== undefined ? String(end) : undefined, - }, + start: start !== undefined ? String(start) : undefined, + end: end !== undefined ? String(end) : undefined, }); return response.ok({ diff --git a/x-pack/platform/plugins/shared/ml/server/routes/job_service.ts b/x-pack/platform/plugins/shared/ml/server/routes/job_service.ts index 8c9f90db38186..a48ec82e95957 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/job_service.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/job_service.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { categorizationExamplesProvider } from '@kbn/ml-category-validator'; import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; diff --git a/x-pack/platform/plugins/shared/ml/server/routes/management.ts b/x-pack/platform/plugins/shared/ml/server/routes/management.ts index 9d81aa06602c1..8cf0e9c9c7349 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/management.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/management.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { BUILT_IN_MODEL_TYPE, BUILT_IN_MODEL_TAG } from '@kbn/ml-trained-models-utils'; import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; diff --git a/x-pack/platform/plugins/shared/ml/server/routes/system.ts b/x-pack/platform/plugins/shared/ml/server/routes/system.ts index 150fc3c75a109..607c82334f116 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/system.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/system.ts @@ -6,7 +6,7 @@ */ import { schema } from '@kbn/config-schema'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ML_INTERNAL_BASE_PATH } from '../../common/constants/app'; import { wrapError } from '../client/error_wrapper'; diff --git a/x-pack/platform/plugins/shared/ml/server/routes/trained_models.ts b/x-pack/platform/plugins/shared/ml/server/routes/trained_models.ts index adedb37b4a7a5..407b3ce80d838 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/trained_models.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/trained_models.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { CloudSetup } from '@kbn/cloud-plugin/server'; import { schema } from '@kbn/config-schema'; import type { ErrorType } from '@kbn/ml-error-utils'; @@ -610,12 +610,10 @@ export function trainedModelsRoutes( const body = await mlClient.inferTrainedModel({ model_id: modelId, deployment_id: deploymentId, - body: { - docs: request.body.docs, - ...(request.body.inference_config - ? { inference_config: request.body.inference_config } - : {}), - }, + docs: request.body.docs, + ...(request.body.inference_config + ? { inference_config: request.body.inference_config } + : {}), ...(request.query.timeout ? { timeout: request.query.timeout } : {}), }); return response.ok({ diff --git a/x-pack/platform/plugins/shared/ml/server/saved_objects/checks.ts b/x-pack/platform/plugins/shared/ml/server/saved_objects/checks.ts index 73a3601ca748b..a690e1d24f4d4 100644 --- a/x-pack/platform/plugins/shared/ml/server/saved_objects/checks.ts +++ b/x-pack/platform/plugins/shared/ml/server/saved_objects/checks.ts @@ -6,7 +6,7 @@ */ import Boom from '@hapi/boom'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient, KibanaRequest, SavedObjectsFindResult } from '@kbn/core/server'; import type { MLSavedObjectService, diff --git a/x-pack/platform/plugins/shared/ml/server/saved_objects/util.ts b/x-pack/platform/plugins/shared/ml/server/saved_objects/util.ts index 7f3f087ea61be..0ccfa3fb02a3c 100644 --- a/x-pack/platform/plugins/shared/ml/server/saved_objects/util.ts +++ b/x-pack/platform/plugins/shared/ml/server/saved_objects/util.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { type SavedObjectsServiceStart, type KibanaRequest, diff --git a/x-pack/platform/plugins/shared/ml/server/shared_services/providers/system.ts b/x-pack/platform/plugins/shared/ml/server/shared_services/providers/system.ts index 2f7437bb58ad7..2f0c7e32504d0 100644 --- a/x-pack/platform/plugins/shared/ml/server/shared_services/providers/system.ts +++ b/x-pack/platform/plugins/shared/ml/server/shared_services/providers/system.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { KibanaRequest, SavedObjectsClientContract } from '@kbn/core/server'; import type { CloudSetup } from '@kbn/cloud-plugin/server'; diff --git a/x-pack/platform/plugins/shared/ml/server/shared_services/providers/trained_models.ts b/x-pack/platform/plugins/shared/ml/server/shared_services/providers/trained_models.ts index 04f12d82688e1..1a5ee2374ee32 100644 --- a/x-pack/platform/plugins/shared/ml/server/shared_services/providers/trained_models.ts +++ b/x-pack/platform/plugins/shared/ml/server/shared_services/providers/trained_models.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { CloudSetup } from '@kbn/cloud-plugin/server'; import type { KibanaRequest, SavedObjectsClientContract } from '@kbn/core/server'; import type { diff --git a/x-pack/platform/plugins/shared/ml/server/usage/collector.ts b/x-pack/platform/plugins/shared/ml/server/usage/collector.ts index c84eebe369d8f..8f1178ba13216 100644 --- a/x-pack/platform/plugins/shared/ml/server/usage/collector.ts +++ b/x-pack/platform/plugins/shared/ml/server/usage/collector.ts @@ -96,25 +96,23 @@ export function registerCollector( { index: alertIndex, size: 0, - body: { - query: { - bool: { - filter: [ - { term: { type: 'alert' } }, - { - term: { - 'alert.alertTypeId': ML_ALERT_TYPES.ANOMALY_DETECTION, - }, + query: { + bool: { + filter: [ + { term: { type: 'alert' } }, + { + term: { + 'alert.alertTypeId': ML_ALERT_TYPES.ANOMALY_DETECTION, }, - ], - }, - }, - aggs: { - count_by_result_type: { - terms: { - field: 'alert.params.resultType', - size: 3, }, + ], + }, + }, + aggs: { + count_by_result_type: { + terms: { + field: 'alert.params.resultType', + size: 3, }, }, }, @@ -143,18 +141,16 @@ export function registerCollector( { index: alertIndex, size: 10000, - body: { - query: { - bool: { - filter: [ - { term: { type: 'alert' } }, - { - term: { - 'alert.alertTypeId': ML_ALERT_TYPES.AD_JOBS_HEALTH, - }, + query: { + bool: { + filter: [ + { term: { type: 'alert' } }, + { + term: { + 'alert.alertTypeId': ML_ALERT_TYPES.AD_JOBS_HEALTH, }, - ], - }, + }, + ], }, }, }, diff --git a/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/inference_endpoint.ts b/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/inference_endpoint.ts index 1822b7766b0b7..e6f9f38a202f1 100644 --- a/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/inference_endpoint.ts +++ b/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/inference_endpoint.ts @@ -130,9 +130,9 @@ export async function getElserModelStatus({ (stats) => stats.deployment_stats?.deployment_id === AI_ASSISTANT_KB_INFERENCE_ID ); const deploymentState = elserModelStats?.deployment_stats?.state; - const allocationState = elserModelStats?.deployment_stats?.allocation_status.state; + const allocationState = elserModelStats?.deployment_stats?.allocation_status?.state; const allocationCount = - elserModelStats?.deployment_stats?.allocation_status.allocation_count ?? 0; + elserModelStats?.deployment_stats?.allocation_status?.allocation_count ?? 0; const ready = deploymentState === 'started' && allocationState === 'fully_allocated' && allocationCount > 0; diff --git a/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/knowledge_base_service/reindex_knowledge_base.ts b/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/knowledge_base_service/reindex_knowledge_base.ts index 7b65576a1e6da..d16ad3b0a77b8 100644 --- a/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/knowledge_base_service/reindex_knowledge_base.ts +++ b/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/knowledge_base_service/reindex_knowledge_base.ts @@ -54,10 +54,8 @@ export async function reIndexKnowledgeBase({ // Perform reindex to temporary index logger.debug(`Re-indexing knowledge base to temporary index "${tempIndex}"...`); await esClient.asInternalUser.reindex({ - body: { - source: { index: originalIndex }, - dest: { index: tempIndex }, - }, + source: { index: originalIndex }, + dest: { index: tempIndex }, refresh: true, wait_for_completion: true, }); @@ -70,10 +68,8 @@ export async function reIndexKnowledgeBase({ // Perform reindex back to original index logger.debug(`Re-indexing knowledge base back to original index "${originalIndex}"...`); await esClient.asInternalUser.reindex({ - body: { - source: { index: tempIndex }, - dest: { index: originalIndex }, - }, + source: { index: tempIndex }, + dest: { index: originalIndex }, refresh: true, wait_for_completion: true, }); diff --git a/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/task_manager_definitions/register_kb_semantic_text_migration_task.ts b/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/task_manager_definitions/register_kb_semantic_text_migration_task.ts index 4f83e61a67a4d..0bcac630c79ca 100644 --- a/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/task_manager_definitions/register_kb_semantic_text_migration_task.ts +++ b/x-pack/platform/plugins/shared/observability_ai_assistant/server/service/task_manager_definitions/register_kb_semantic_text_migration_task.ts @@ -195,11 +195,9 @@ async function populateSemanticTextFieldRecursively({ refresh: 'wait_for', index: resourceNames.aliases.kb, id: hit._id, - body: { - doc: { - ...hit._source, - semantic_text: hit._source.text, - }, + doc: { + ...hit._source, + semantic_text: hit._source.text, }, }); }); diff --git a/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/actions/index.ts b/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/actions/index.ts index 3511b4e63d66c..b7b5ada60450b 100644 --- a/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/actions/index.ts +++ b/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/actions/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IEsSearchResponse } from '@kbn/search-types'; import type { IKibanaSearchResponse } from '@kbn/search-types'; import type { Inspect, Maybe } from '../../common'; diff --git a/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/results/index.ts b/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/results/index.ts index a40ac4b961640..32cbea01fd6e5 100644 --- a/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/results/index.ts +++ b/x-pack/platform/plugins/shared/osquery/common/search_strategy/osquery/results/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IEsSearchResponse } from '@kbn/search-types'; import type { Inspect, Maybe, SortField } from '../../common'; diff --git a/x-pack/platform/plugins/shared/osquery/common/utils/aggregations.ts b/x-pack/platform/plugins/shared/osquery/common/utils/aggregations.ts index c4afef4025ce5..82e7c0f7b00eb 100644 --- a/x-pack/platform/plugins/shared/osquery/common/utils/aggregations.ts +++ b/x-pack/platform/plugins/shared/osquery/common/utils/aggregations.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; interface BaseDataPoint { key: string; diff --git a/x-pack/platform/plugins/shared/osquery/public/action_results/use_action_results.ts b/x-pack/platform/plugins/shared/osquery/public/action_results/use_action_results.ts index 8c20e4ed1c602..7e0eef9b29120 100644 --- a/x-pack/platform/plugins/shared/osquery/public/action_results/use_action_results.ts +++ b/x-pack/platform/plugins/shared/osquery/public/action_results/use_action_results.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { flatten, reverse, uniqBy } from 'lodash/fp'; import { useQuery } from '@tanstack/react-query'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts index 7138c93f06830..7d3540df96a1c 100644 --- a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts +++ b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ISearchRequestParams } from '@kbn/search-types'; import { AGENT_ACTIONS_INDEX } from '@kbn/fleet-plugin/common'; @@ -27,39 +27,37 @@ export const buildActionsQuery = ({ allow_no_indices: true, index: componentTemplateExists ? `${ACTIONS_INDEX}*` : AGENT_ACTIONS_INDEX, ignore_unavailable: true, - body: { - query: { - bool: { - filter, - must: [ - { - term: { - type: { - value: 'INPUT_ACTION', - }, + query: { + bool: { + filter, + must: [ + { + term: { + type: { + value: 'INPUT_ACTION', }, }, - { - term: { - input_type: { - value: 'osquery', - }, + }, + { + term: { + input_type: { + value: 'osquery', }, }, - ] as estypes.QueryDslQueryContainer[], - }, - }, - from: cursorStart, - size: querySize, - track_total_hits: true, - fields: ['*'], - sort: [ - { - [sort.field]: { - order: sort.direction, }, - }, - ], + ] as estypes.QueryDslQueryContainer[], + }, }, + from: cursorStart, + size: querySize, + track_total_hits: true, + fields: ['*'], + sort: [ + { + [sort.field]: { + order: sort.direction, + }, + }, + ], }; }; diff --git a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/details/query.action_details.dsl.ts b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/details/query.action_details.dsl.ts index 6b3c6564c994e..6f179bd62ef31 100644 --- a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/details/query.action_details.dsl.ts +++ b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/details/query.action_details.dsl.ts @@ -29,11 +29,9 @@ export const buildActionDetailsQuery = ({ allow_no_indices: true, index: componentTemplateExists ? `${ACTIONS_INDEX}*` : AGENT_ACTIONS_INDEX, ignore_unavailable: true, - body: { - query: { bool: { filter: filterQuery } }, - size: 1, - fields: ['*'], - }, + query: { bool: { filter: filterQuery } }, + size: 1, + fields: ['*'], }; return dslQuery; diff --git a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts index 18a9c4fab8332..661182d12292f 100644 --- a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts +++ b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts @@ -58,55 +58,53 @@ export const buildActionResultsQuery = ({ allow_no_indices: true, index, ignore_unavailable: true, - body: { + aggs: { aggs: { + global: {}, aggs: { - global: {}, - aggs: { - responses_by_action_id: { - filter: { - bool: { - must: [ - { - match: { - action_id: actionId, - }, + responses_by_action_id: { + filter: { + bool: { + must: [ + { + match: { + action_id: actionId, }, - ], - }, - }, - aggs: { - rows_count: { - sum: { - field: 'action_response.osquery.count', }, + ], + }, + }, + aggs: { + rows_count: { + sum: { + field: 'action_response.osquery.count', }, - responses: { - terms: { - script: { - lang: 'painless', - source: - "if (doc['error.keyword'].size()==0) { return 'success' } else { return 'error' }", - } as const, - }, + }, + responses: { + terms: { + script: { + lang: 'painless', + source: + "if (doc['error.keyword'].size()==0) { return 'success' } else { return 'error' }", + } as const, }, }, }, }, }, }, - query: { bool: { filter: filterQuery } }, - // from: activePage * querySize, - size: 10000, // querySize, - track_total_hits: true, - fields: ['*'], - sort: [ - { - [sort.field]: { - order: sort.direction, - }, - }, - ], }, + query: { bool: { filter: filterQuery } }, + // from: activePage * querySize, + size: 10000, // querySize, + track_total_hits: true, + fields: ['*'], + sort: [ + { + [sort.field]: { + order: sort.direction, + }, + }, + ], }; }; diff --git a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/results/query.all_results.dsl.ts b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/results/query.all_results.dsl.ts index 6a8e85f657218..b3e8e000c0221 100644 --- a/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/results/query.all_results.dsl.ts +++ b/x-pack/platform/plugins/shared/osquery/server/search_strategy/osquery/factory/results/query.all_results.dsl.ts @@ -46,31 +46,29 @@ export const buildResultsQuery = ({ allow_no_indices: true, index: `logs-${OSQUERY_INTEGRATION_NAME}.result*`, ignore_unavailable: true, - body: { - aggs: { - count_by_agent_id: { - terms: { - field: 'elastic_agent.id', - size: 10000, - }, + aggs: { + count_by_agent_id: { + terms: { + field: 'elastic_agent.id', + size: 10000, }, - unique_agents: { - cardinality: { - field: 'elastic_agent.id', - }, + }, + unique_agents: { + cardinality: { + field: 'elastic_agent.id', }, }, - query: { bool: { filter: filterQuery } }, - from: activePage * querySize, - size: querySize, - track_total_hits: true, - fields: ['elastic_agent.*', 'agent.*', 'osquery.*'], - sort: - sort?.map((sortConfig) => ({ - [sortConfig.field]: { - order: sortConfig.direction, - }, - })) ?? [], }, + query: { bool: { filter: filterQuery } }, + from: activePage * querySize, + size: querySize, + track_total_hits: true, + fields: ['elastic_agent.*', 'agent.*', 'osquery.*'], + sort: + sort?.map((sortConfig) => ({ + [sortConfig.field]: { + order: sortConfig.direction, + }, + })) ?? [], }; }; diff --git a/x-pack/platform/plugins/shared/rule_registry/common/types.ts b/x-pack/platform/plugins/shared/rule_registry/common/types.ts index 684160bf904d2..a6a39d5f67c5a 100644 --- a/x-pack/platform/plugins/shared/rule_registry/common/types.ts +++ b/x-pack/platform/plugins/shared/rule_registry/common/types.ts @@ -5,9 +5,9 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import * as t from 'io-ts'; -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; // note: these schemas are not exhaustive. See the `Sort` type of `@elastic/elasticsearch` if you need to enhance it. const fieldSchema = t.string; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.test.ts index 77215955277dc..d637c9b099600 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.test.ts @@ -60,90 +60,88 @@ describe('AlertsClient', () => { expect(esClientMock.search.mock.calls[0][0]).toMatchInlineSnapshot(` Object { - "body": Object { - "_source": undefined, - "aggs": undefined, - "fields": Array [ - "kibana.alert.rule.rule_type_id", - "kibana.alert.rule.consumer", - "kibana.alert.workflow_status", - "kibana.space_ids", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "arguments": Array [ - Object { - "arguments": Array [ - Object { - "isQuoted": false, - "type": "literal", - "value": "alert.attributes.alertTypeId", - }, - Object { - "isQuoted": false, - "type": "literal", - "value": "test-rule-type-1", - }, - ], - "function": "is", - "type": "function", - }, - Object { - "arguments": Array [ - Object { - "isQuoted": false, - "type": "literal", - "value": "alert.attributes.consumer", - }, - Object { - "isQuoted": false, - "type": "literal", - "value": "foo", - }, - ], - "function": "is", - "type": "function", - }, - ], - "function": "and", - "type": "function", - }, - Object { - "term": Object { - "kibana.space_ids": "space-1", + "_source": undefined, + "aggs": undefined, + "fields": Array [ + "kibana.alert.rule.rule_type_id", + "kibana.alert.rule.consumer", + "kibana.alert.workflow_status", + "kibana.space_ids", + ], + "ignore_unavailable": true, + "index": ".alerts-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "arguments": Array [ + Object { + "arguments": Array [ + Object { + "isQuoted": false, + "type": "literal", + "value": "alert.attributes.alertTypeId", + }, + Object { + "isQuoted": false, + "type": "literal", + "value": "test-rule-type-1", + }, + ], + "function": "is", + "type": "function", }, - }, - Object { - "terms": Object { - "kibana.alert.rule.rule_type_id": Array [ - "test-rule-type-1", - "test-rule-type-2", + Object { + "arguments": Array [ + Object { + "isQuoted": false, + "type": "literal", + "value": "alert.attributes.consumer", + }, + Object { + "isQuoted": false, + "type": "literal", + "value": "foo", + }, ], + "function": "is", + "type": "function", }, + ], + "function": "and", + "type": "function", + }, + Object { + "term": Object { + "kibana.space_ids": "space-1", }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, - }, - "runtime_mappings": undefined, - "size": undefined, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", - "unmapped_type": "date", }, - }, - ], - "track_total_hits": undefined, + Object { + "terms": Object { + "kibana.alert.rule.rule_type_id": Array [ + "test-rule-type-1", + "test-rule-type-2", + ], + }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, }, - "ignore_unavailable": true, - "index": ".alerts-*", + "runtime_mappings": undefined, "seq_no_primary_term": true, + "size": undefined, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + "unmapped_type": "date", + }, + }, + ], + "track_total_hits": undefined, } `); }); @@ -153,90 +151,88 @@ describe('AlertsClient', () => { expect(esClientMock.search.mock.calls[0][0]).toMatchInlineSnapshot(` Object { - "body": Object { - "_source": undefined, - "aggs": undefined, - "fields": Array [ - "kibana.alert.rule.rule_type_id", - "kibana.alert.rule.consumer", - "kibana.alert.workflow_status", - "kibana.space_ids", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "arguments": Array [ - Object { - "arguments": Array [ - Object { - "isQuoted": false, - "type": "literal", - "value": "alert.attributes.alertTypeId", - }, - Object { - "isQuoted": false, - "type": "literal", - "value": "test-rule-type-1", - }, - ], - "function": "is", - "type": "function", - }, - Object { - "arguments": Array [ - Object { - "isQuoted": false, - "type": "literal", - "value": "alert.attributes.consumer", - }, - Object { - "isQuoted": false, - "type": "literal", - "value": "foo", - }, - ], - "function": "is", - "type": "function", - }, - ], - "function": "and", - "type": "function", - }, - Object { - "term": Object { - "kibana.space_ids": "space-1", + "_source": undefined, + "aggs": undefined, + "fields": Array [ + "kibana.alert.rule.rule_type_id", + "kibana.alert.rule.consumer", + "kibana.alert.workflow_status", + "kibana.space_ids", + ], + "ignore_unavailable": true, + "index": ".alerts-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "arguments": Array [ + Object { + "arguments": Array [ + Object { + "isQuoted": false, + "type": "literal", + "value": "alert.attributes.alertTypeId", + }, + Object { + "isQuoted": false, + "type": "literal", + "value": "test-rule-type-1", + }, + ], + "function": "is", + "type": "function", }, - }, - Object { - "terms": Object { - "kibana.alert.rule.consumer": Array [ - "test-consumer-1", - "test-consumer-2", + Object { + "arguments": Array [ + Object { + "isQuoted": false, + "type": "literal", + "value": "alert.attributes.consumer", + }, + Object { + "isQuoted": false, + "type": "literal", + "value": "foo", + }, ], + "function": "is", + "type": "function", }, + ], + "function": "and", + "type": "function", + }, + Object { + "term": Object { + "kibana.space_ids": "space-1", }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, - }, - "runtime_mappings": undefined, - "size": undefined, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", - "unmapped_type": "date", }, - }, - ], - "track_total_hits": undefined, + Object { + "terms": Object { + "kibana.alert.rule.consumer": Array [ + "test-consumer-1", + "test-consumer-2", + ], + }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, }, - "ignore_unavailable": true, - "index": ".alerts-*", + "runtime_mappings": undefined, "seq_no_primary_term": true, + "size": undefined, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + "unmapped_type": "date", + }, + }, + ], + "track_total_hits": undefined, } `); }); diff --git a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.ts b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.ts index 3a898b07fb461..ae7eb4caea82b 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/alerts_client.ts @@ -6,7 +6,7 @@ */ import Boom from '@hapi/boom'; import { v4 as uuidv4 } from 'uuid'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { PublicMethodsOf } from '@kbn/utility-types'; import { Filter, buildEsQuery, EsQueryConfig } from '@kbn/es-query'; import { decodeVersion, encodeHitVersion } from '@kbn/securitysolution-es-utils'; @@ -307,7 +307,7 @@ export class AlertsClient { const config = getEsQueryConfig(); - let queryBody: estypes.SearchRequest['body'] = { + let queryBody: estypes.SearchRequest = { fields: [ALERT_RULE_TYPE_ID, ALERT_RULE_CONSUMER, ALERT_WORKFLOW_STATUS, SPACE_IDS], query: await this.buildEsQueryWithAuthz( query, @@ -343,7 +343,7 @@ export class AlertsClient { const result = await this.esClient.search({ index: index ?? '.alerts-*', ignore_unavailable: true, - body: queryBody, + ...queryBody, seq_no_primary_term: true, }); @@ -781,10 +781,8 @@ export class AlertsClient { ...decodeVersion(_version), id, index, - body: { - doc: { - ...fieldToUpdate, - }, + doc: { + ...fieldToUpdate, }, refresh: 'wait_for', }); diff --git a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/find_alerts.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/find_alerts.test.ts index c554ee4d61f99..83b9d8b8d10c4 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/find_alerts.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/find_alerts.test.ts @@ -215,139 +215,137 @@ describe('find()', () => { expect(esClientMock.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "_source": undefined, - "aggs": undefined, - "fields": Array [ - "kibana.alert.rule.rule_type_id", - "kibana.alert.rule.consumer", - "kibana.alert.workflow_status", - "kibana.space_ids", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.rule_type_id": ".es-query", - }, + "_source": undefined, + "aggs": undefined, + "fields": Array [ + "kibana.alert.rule.rule_type_id", + "kibana.alert.rule.consumer", + "kibana.alert.workflow_status", + "kibana.space_ids", + ], + "ignore_unavailable": true, + "index": ".alerts-observability.apm.alerts", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.rule_type_id": ".es-query", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.consumer": "stackAlerts", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.consumer": "stackAlerts", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.consumer": "alerts", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.consumer": "alerts", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "default", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "default", }, - Object { - "terms": Object { - "kibana.alert.rule.rule_type_id": Array [ - ".es-query", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.rule_type_id": Array [ + ".es-query", + ], }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "test_default_space_id", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "test_default_space_id", }, - Object { - "terms": Object { - "kibana.alert.rule.rule_type_id": Array [ - "siem.esqlRule", - "siem.eqlRule", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.rule_type_id": Array [ + "siem.esqlRule", + "siem.eqlRule", + ], }, - Object { - "terms": Object { - "kibana.alert.rule.consumer": Array [ - "siem", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.consumer": Array [ + "siem", + ], }, - ], - "must": Array [ - Object { - "match": Object { - "kibana.alert.workflow_status": "open", - }, + }, + ], + "must": Array [ + Object { + "match": Object { + "kibana.alert.workflow_status": "open", }, - ], - "must_not": Array [], - "should": Array [], - }, - }, - "runtime_mappings": undefined, - "size": undefined, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", - "unmapped_type": "date", }, - }, - ], - "track_total_hits": undefined, + ], + "must_not": Array [], + "should": Array [], + }, }, - "ignore_unavailable": true, - "index": ".alerts-observability.apm.alerts", + "runtime_mappings": undefined, "seq_no_primary_term": true, + "size": undefined, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + "unmapped_type": "date", + }, + }, + ], + "track_total_hits": undefined, }, ] `); @@ -437,121 +435,119 @@ describe('find()', () => { expect(esClientMock.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "_source": undefined, - "aggs": undefined, - "fields": Array [ - "kibana.alert.rule.rule_type_id", - "kibana.alert.rule.consumer", - "kibana.alert.workflow_status", - "kibana.space_ids", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.rule_type_id": ".es-query", - }, + "_source": undefined, + "aggs": undefined, + "fields": Array [ + "kibana.alert.rule.rule_type_id", + "kibana.alert.rule.consumer", + "kibana.alert.workflow_status", + "kibana.space_ids", + ], + "ignore_unavailable": true, + "index": ".alerts-observability.apm.alerts", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.rule_type_id": ".es-query", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.consumer": "stackAlerts", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.consumer": "stackAlerts", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.consumer": "alerts", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.consumer": "alerts", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "default", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "default", }, - Object { - "terms": Object { - "kibana.alert.rule.rule_type_id": Array [ - ".es-query", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.rule_type_id": Array [ + ".es-query", + ], }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "test_default_space_id", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "test_default_space_id", }, - ], - "must": Array [ - Object { - "match": Object { - "kibana.alert.workflow_status": "open", - }, + }, + ], + "must": Array [ + Object { + "match": Object { + "kibana.alert.workflow_status": "open", }, - ], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must_not": Array [], + "should": Array [], }, - "runtime_mappings": undefined, - "size": undefined, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - "track_total_hits": undefined, }, - "ignore_unavailable": true, - "index": ".alerts-observability.apm.alerts", + "runtime_mappings": undefined, "seq_no_primary_term": true, + "size": undefined, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], + "track_total_hits": undefined, }, ] `); diff --git a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get.test.ts index b0fcb505d95b6..2c8b37571a672 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get.test.ts @@ -122,56 +122,54 @@ describe('get()', () => { expect(esClientMock.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "_source": undefined, - "aggs": undefined, - "fields": Array [ - "kibana.alert.rule.rule_type_id", - "kibana.alert.rule.consumer", - "kibana.alert.workflow_status", - "kibana.space_ids", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "_id": "1", - }, + "_source": undefined, + "aggs": undefined, + "fields": Array [ + "kibana.alert.rule.rule_type_id", + "kibana.alert.rule.consumer", + "kibana.alert.workflow_status", + "kibana.space_ids", + ], + "ignore_unavailable": true, + "index": ".alerts-observability.apm.alerts", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "_id": "1", }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "test_default_space_id", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "test_default_space_id", }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, - }, - "runtime_mappings": undefined, - "size": undefined, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", - "unmapped_type": "date", }, - }, - ], - "track_total_hits": undefined, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, }, - "ignore_unavailable": true, - "index": ".alerts-observability.apm.alerts", + "runtime_mappings": undefined, "seq_no_primary_term": true, + "size": undefined, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + "unmapped_type": "date", + }, + }, + ], + "track_total_hits": undefined, }, ] `); diff --git a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get_alerts_summary.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get_alerts_summary.test.ts index deb3b82058843..fe08fea3d5756 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get_alerts_summary.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/get_alerts_summary.test.ts @@ -121,188 +121,186 @@ describe('getAlertSummary()', () => { Array [ Array [ Object { - "body": Object { - "_source": undefined, - "aggs": Object { - "active_alerts_bucket": Object { - "date_histogram": Object { - "extended_bounds": Object { - "max": "now/d", - "min": "now-1d/d", - }, - "field": "kibana.alert.time_range", - "fixed_interval": "1m", - "hard_bounds": Object { - "max": "now/d", - "min": "now-1d/d", - }, - "min_doc_count": 0, + "_source": undefined, + "aggs": Object { + "active_alerts_bucket": Object { + "date_histogram": Object { + "extended_bounds": Object { + "max": "now/d", + "min": "now-1d/d", }, - }, - "count": Object { - "terms": Object { - "field": "kibana.alert.status", + "field": "kibana.alert.time_range", + "fixed_interval": "1m", + "hard_bounds": Object { + "max": "now/d", + "min": "now-1d/d", }, + "min_doc_count": 0, }, - "recovered_alerts": Object { - "aggs": Object { - "container": Object { - "date_histogram": Object { - "extended_bounds": Object { - "max": "now/d", - "min": "now-1d/d", - }, - "field": "kibana.alert.end", - "fixed_interval": "1m", - "min_doc_count": 0, + }, + "count": Object { + "terms": Object { + "field": "kibana.alert.status", + }, + }, + "recovered_alerts": Object { + "aggs": Object { + "container": Object { + "date_histogram": Object { + "extended_bounds": Object { + "max": "now/d", + "min": "now-1d/d", }, + "field": "kibana.alert.end", + "fixed_interval": "1m", + "min_doc_count": 0, }, }, - "filter": Object { - "term": Object { - "kibana.alert.status": "recovered", - }, + }, + "filter": Object { + "term": Object { + "kibana.alert.status": "recovered", }, }, }, - "fields": Array [ - "kibana.alert.rule.rule_type_id", - "kibana.alert.rule.consumer", - "kibana.alert.workflow_status", - "kibana.space_ids", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.rule_type_id": ".es-query", - }, + }, + "fields": Array [ + "kibana.alert.rule.rule_type_id", + "kibana.alert.rule.consumer", + "kibana.alert.workflow_status", + "kibana.space_ids", + ], + "ignore_unavailable": true, + "index": "stack-index", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.rule_type_id": ".es-query", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.consumer": "stackAlerts", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.consumer": "stackAlerts", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "kibana.alert.rule.consumer": "alerts", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "kibana.alert.rule.consumer": "alerts", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "default", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "default", }, - Object { - "terms": Object { - "kibana.alert.rule.rule_type_id": Array [ - ".es-query", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.rule_type_id": Array [ + ".es-query", + ], }, - ], - }, + }, + ], }, - Object { - "term": Object { - "kibana.space_ids": "test_default_space_id", - }, + }, + Object { + "term": Object { + "kibana.space_ids": "test_default_space_id", }, - Object { - "terms": Object { - "kibana.alert.rule.rule_type_id": Array [ - ".es-query", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.rule_type_id": Array [ + ".es-query", + ], }, - Object { - "terms": Object { - "kibana.alert.rule.consumer": Array [ - "stackAlerts", - ], - }, + }, + Object { + "terms": Object { + "kibana.alert.rule.consumer": Array [ + "stackAlerts", + ], }, - ], - "must": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "kibana.alert.time_range": Object { - "gt": "now-1d/d", - "lt": "now/d", - }, + }, + ], + "must": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "kibana.alert.time_range": Object { + "gt": "now-1d/d", + "lt": "now/d", }, }, - ], - }, + }, + ], }, - ], - "must_not": Array [], - "should": Array [], - }, - }, - "runtime_mappings": undefined, - "size": 0, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", - "unmapped_type": "date", }, - }, - ], - "track_total_hits": undefined, + ], + "must_not": Array [], + "should": Array [], + }, }, - "ignore_unavailable": true, - "index": "stack-index", + "runtime_mappings": undefined, "seq_no_primary_term": true, + "size": 0, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + "unmapped_type": "date", + }, + }, + ], + "track_total_hits": undefined, }, ], ] diff --git a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/update.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/update.test.ts index 4b9587b8e0ca1..be7f804239b54 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/update.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/alert_data_client/tests/update.test.ts @@ -135,10 +135,8 @@ describe('update()', () => { expect(esClientMock.update.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "doc": Object { - "${ALERT_WORKFLOW_STATUS}": "closed", - }, + "doc": Object { + "kibana.alert.workflow_status": "closed", }, "id": "1", "index": ".alerts-observability.apm.alerts", diff --git a/x-pack/platform/plugins/shared/rule_registry/server/routes/find.ts b/x-pack/platform/plugins/shared/rule_registry/server/routes/find.ts index d41de4d64f71f..3e0ccb94db6b7 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/routes/find.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/routes/find.ts @@ -9,7 +9,7 @@ import { IRouter } from '@kbn/core/server'; import * as t from 'io-ts'; import { transformError } from '@kbn/securitysolution-es-utils'; import { PositiveInteger } from '@kbn/securitysolution-io-ts-types'; -import { SortOptions } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SortOptions } from '@elastic/elasticsearch/lib/api/types'; import { bucketAggsSchemas, metricsAggsSchemas } from '../../common/types'; import { RacRequestHandlerContext } from '../types'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alert_summary.ts b/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alert_summary.ts index 9be3de57fdc0a..3a4de681cd9bf 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alert_summary.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alert_summary.ts @@ -10,7 +10,7 @@ import { IRouter } from '@kbn/core/server'; import * as t from 'io-ts'; import { transformError } from '@kbn/securitysolution-es-utils'; import moment from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RacRequestHandlerContext } from '../types'; import { BASE_RAC_ALERTS_API_PATH } from '../../common/constants'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alerts_group_aggregations.ts b/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alerts_group_aggregations.ts index 6924025f2b33a..67d37b09b3d46 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alerts_group_aggregations.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/routes/get_alerts_group_aggregations.ts @@ -9,7 +9,7 @@ import { IRouter } from '@kbn/core/server'; import * as t from 'io-ts'; import { transformError } from '@kbn/securitysolution-es-utils'; -import { SortCombinations } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SortCombinations } from '@elastic/elasticsearch/lib/api/types'; import { RacRequestHandlerContext } from '../types'; import { BASE_RAC_ALERTS_API_PATH } from '../../common/constants'; import { buildRouteValidation } from './utils/route_validation'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.test.ts index 8898b8634b293..8ce15929b8e3a 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.test.ts @@ -7,7 +7,7 @@ import { left, right } from 'fp-ts/lib/Either'; import { errors } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { RuleDataClient, RuleDataClientConstructorOptions, WaitResult } from './rule_data_client'; import { IndexInfo } from '../rule_data_plugin_service/index_info'; @@ -107,12 +107,10 @@ describe('RuleDataClient', () => { const query = { query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } } }; const reader = ruleDataClient.getReader(); - await reader.search({ - body: query, - }); + await reader.search(query); expect(scopedClusterClient.search).toHaveBeenCalledWith({ - body: query, + ...query, ignore_unavailable: true, index: `.alerts-observability.apm.alerts*`, seq_no_primary_term: true, @@ -131,12 +129,10 @@ describe('RuleDataClient', () => { const query = { query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } } }; const reader = ruleDataClient.getReader({ namespace: 'test' }); - await reader.search({ - body: query, - }); + await reader.search(query); expect(scopedClusterClient.search).toHaveBeenCalledWith({ - body: query, + ...query, ignore_unavailable: true, index: `.alerts-observability.apm.alerts-test`, seq_no_primary_term: true, @@ -151,11 +147,9 @@ describe('RuleDataClient', () => { const query = { query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } } }; const reader = ruleDataClient.getReader(); - await expect( - reader.search({ - body: query, - }) - ).rejects.toThrowErrorMatchingInlineSnapshot(`"something went wrong!"`); + await expect(reader.search(query)).rejects.toThrowErrorMatchingInlineSnapshot( + `"something went wrong!"` + ); expect(logger.error).toHaveBeenCalledWith( `Error performing search in RuleDataClient - something went wrong!` @@ -224,11 +218,9 @@ describe('RuleDataClient', () => { const query = { query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } } }; const reader = ruleDataClient.getReader(); - await expect( - reader.search({ - body: query, - }) - ).rejects.toThrowErrorMatchingInlineSnapshot(`"could not get cluster client"`); + await expect(reader.search(query)).rejects.toThrowErrorMatchingInlineSnapshot( + `"could not get cluster client"` + ); await expect(reader.getDynamicIndexPattern()).rejects.toThrowErrorMatchingInlineSnapshot( `"could not get cluster client"` diff --git a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.ts b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.ts index 329c060426093..708999f786961 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/rule_data_client.ts @@ -6,7 +6,7 @@ */ import { errors, TransportResult } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Either, isLeft } from 'fp-ts/lib/Either'; import { ElasticsearchClient } from '@kbn/core/server'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/types.ts b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/types.ts index a7da8069739f4..8e7a77d537cfd 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/types.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_client/types.ts @@ -6,7 +6,7 @@ */ import type { TransportResult } from '@elastic/elasticsearch'; -import { BulkRequest, BulkResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { BulkRequest, BulkResponse } from '@elastic/elasticsearch/lib/api/types'; import type { ESSearchRequest, ESSearchResponse } from '@kbn/es-types'; import { FieldDescriptor } from '@kbn/data-plugin/server'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/index_options.ts b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/index_options.ts index cdec7c609699d..c3858194846ba 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/index_options.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/index_options.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ValidFeatureId } from '@kbn/rule-data-utils'; /** diff --git a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts index d2011139adbb7..d26375575c3e2 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts @@ -13,7 +13,7 @@ import { IndicesGetDataStreamResponse, IndicesDataStreamIndex, IndicesDataStream, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { Dataset } from './index_options'; import { IndexInfo } from './index_info'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.ts b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.ts index 2a6533d7e1002..59c9928d5358b 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/rule_data_plugin_service/resource_installer.ts @@ -93,8 +93,8 @@ export class ResourceInstaller { logger, esClient: clusterClient, template: { + ...ecsComponentTemplate, name: ECS_COMPONENT_TEMPLATE_NAME, - body: ecsComponentTemplate, }, totalFieldsLimit: TOTAL_FIELDS_LIMIT, }), @@ -103,8 +103,8 @@ export class ResourceInstaller { logger, esClient: clusterClient, template: { + ...technicalComponentTemplate, name: TECHNICAL_COMPONENT_TEMPLATE_NAME, - body: technicalComponentTemplate, }, totalFieldsLimit: TOTAL_FIELDS_LIMIT, }), @@ -168,13 +168,11 @@ export class ResourceInstaller { esClient: clusterClient, template: { name: indexInfo.getComponentTemplateName(ct.name), - body: { - template: { - settings: ct.settings ?? {}, - mappings: ct.mappings, - }, - _meta: ct._meta, + template: { + settings: ct.settings ?? {}, + mappings: ct.mappings, }, + _meta: ct._meta, }, totalFieldsLimit: TOTAL_FIELDS_LIMIT, }); diff --git a/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts b/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts index bfecc958ce3d1..d5386e5513f04 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts @@ -7,7 +7,7 @@ import Boom from '@hapi/boom'; import { map, mergeMap, catchError, of } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Logger } from '@kbn/core/server'; import { from } from 'rxjs'; import { ENHANCED_ES_SEARCH_STRATEGY } from '@kbn/data-plugin/common'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.test.ts index 7e1e420859087..7bd1beea20a9c 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ALERT_INSTANCE_ID, diff --git a/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.ts b/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.ts index 892ba70d247ed..fcbf55d600edf 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/utils/create_persistence_rule_type_wrapper.ts @@ -7,7 +7,7 @@ import sortBy from 'lodash/sortBy'; import dateMath from '@elastic/datemath'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RuleExecutorOptions } from '@kbn/alerting-plugin/server'; import { chunk, partition } from 'lodash'; import { @@ -108,22 +108,20 @@ const filterDuplicateAlerts = async ({ for (const alertChunk of alertChunks) { const request: estypes.SearchRequest = { - body: { - query: { - ids: { - values: alertChunk.map((alert) => alert._id), - }, + query: { + ids: { + values: alertChunk.map((alert) => alert._id), }, - aggs: { - uuids: { - terms: { - field: ALERT_UUID, - size: CHUNK_SIZE, - }, + }, + aggs: { + uuids: { + terms: { + field: ALERT_UUID, + size: CHUNK_SIZE, }, }, - size: 0, }, + size: 0, }; const response = await ruleDataClient.getReader({ namespace: spaceId }).search(request); const uuidsMap: Record = {}; @@ -413,48 +411,46 @@ export const createPersistenceRuleTypeWrapper: CreatePersistenceRuleTypeWrapper } const suppressionAlertSearchRequest = { - body: { - size: filteredDuplicates.length, - query: { - bool: { - filter: [ - { - range: { - [ALERT_START]: { - gte: suppressionWindowStart.toISOString(), - }, + size: filteredDuplicates.length, + query: { + bool: { + filter: [ + { + range: { + [ALERT_START]: { + gte: suppressionWindowStart.toISOString(), }, }, - { - terms: { - [ALERT_INSTANCE_ID]: filteredDuplicates.map( - (alert) => alert._source[ALERT_INSTANCE_ID] - ), - }, + }, + { + terms: { + [ALERT_INSTANCE_ID]: filteredDuplicates.map( + (alert) => alert._source[ALERT_INSTANCE_ID] + ), }, - { - bool: { - must_not: { - term: { - [ALERT_WORKFLOW_STATUS]: 'closed', - }, + }, + { + bool: { + must_not: { + term: { + [ALERT_WORKFLOW_STATUS]: 'closed', }, }, }, - ], - }, - }, - collapse: { - field: ALERT_INSTANCE_ID, - }, - sort: [ - { - [ALERT_START]: { - order: 'desc' as const, }, - }, - ], + ], + }, }, + collapse: { + field: ALERT_INSTANCE_ID, + }, + sort: [ + { + [ALERT_START]: { + order: 'desc' as const, + }, + }, + ], }; const response = await ruleDataClient diff --git a/x-pack/platform/plugins/shared/rule_registry/server/utils/fetch_alert_by_uuid.ts b/x-pack/platform/plugins/shared/rule_registry/server/utils/fetch_alert_by_uuid.ts index f49da260f6c75..bb90ea3a0b7fa 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/utils/fetch_alert_by_uuid.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/utils/fetch_alert_by_uuid.ts @@ -13,20 +13,18 @@ type RuleDataClient = PublicContract; export const fetchAlertByAlertUUID = async (ruleDataClient: RuleDataClient, alertUuid: string) => { const request = { - body: { - query: { - bool: { - filter: [ - { - term: { - [ALERT_UUID]: alertUuid, - }, + query: { + bool: { + filter: [ + { + term: { + [ALERT_UUID]: alertUuid, }, - ], - }, + }, + ], }, - size: 1, }, + size: 1, allow_no_indices: true, }; const { hits } = await ruleDataClient.getReader().search(request); diff --git a/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.test.ts b/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.test.ts index 57a8c7dd37936..34f82da1e58a1 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.test.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { errorAggregator } from './utils'; import { BulkResponseErrorAggregation } from './utils'; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.ts b/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.ts index 8a7de1cb9c24a..636483a9e27d1 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/utils/utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type BulkResponseErrorAggregation = Record; diff --git a/x-pack/platform/plugins/shared/saved_objects_tagging/server/usage/fetch_tag_usage_data.ts b/x-pack/platform/plugins/shared/saved_objects_tagging/server/usage/fetch_tag_usage_data.ts index a98b39888a6cc..f0465ff7ae08f 100644 --- a/x-pack/platform/plugins/shared/saved_objects_tagging/server/usage/fetch_tag_usage_data.ts +++ b/x-pack/platform/plugins/shared/saved_objects_tagging/server/usage/fetch_tag_usage_data.ts @@ -40,15 +40,13 @@ export const fetchTagUsageData = async ({ index: kibanaIndices, ignore_unavailable: true, filter_path: 'aggregations', - body: { - size: 0, - query: { - bool: { - must: [hasTagReferenceClause], - }, + size: 0, + query: { + bool: { + must: [hasTagReferenceClause], }, - aggs: tagDataAggregations, }, + aggs: tagDataAggregations, }); const byTypeUsages: Record = {}; diff --git a/x-pack/platform/plugins/shared/searchprofiler/server/routes/profile.ts b/x-pack/platform/plugins/shared/searchprofiler/server/routes/profile.ts index 286c8949240fb..796e67b454dd0 100644 --- a/x-pack/platform/plugins/shared/searchprofiler/server/routes/profile.ts +++ b/x-pack/platform/plugins/shared/searchprofiler/server/routes/profile.ts @@ -42,11 +42,9 @@ export const register = ({ router, getLicenseStatus, log }: RouteDependencies) = const body = { index, - body: { - // Activate profiler mode for this query. - profile: true, - ...query, - }, + // Activate profiler mode for this query. + profile: true, + ...query, }; try { diff --git a/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.test.ts b/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.test.ts index 198bc004ecb60..4b078680df826 100644 --- a/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.test.ts +++ b/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.test.ts @@ -134,9 +134,7 @@ describe('API Keys', () => { const result = await apiKeys.areAPIKeysEnabled(); expect(result).toEqual(true); expect(mockClusterClient.asInternalUser.security.invalidateApiKey).toHaveBeenCalledWith({ - body: { - ids: ['kibana-api-key-service-test'], - }, + ids: ['kibana-api-key-service-test'], }); }); }); @@ -253,11 +251,9 @@ describe('API Keys', () => { expect(mockValidateKibanaPrivileges).not.toHaveBeenCalled(); // this is only called if kibana_role_descriptors is defined expect(mockScopedClusterClient.asCurrentUser.transport.request).not.toHaveBeenCalled(); expect(mockScopedClusterClient.asCurrentUser.security.createApiKey).toHaveBeenCalledWith({ - body: { - name: 'key-name', - role_descriptors: roleDescriptors, - expiration: '1d', - }, + name: 'key-name', + role_descriptors: roleDescriptors, + expiration: '1d', }); }); @@ -636,9 +632,7 @@ describe('API Keys', () => { error_details: [], }); expect(mockScopedClusterClient.asCurrentUser.security.invalidateApiKey).toHaveBeenCalledWith({ - body: { - ids: ['123'], - }, + ids: ['123'], }); }); @@ -661,9 +655,7 @@ describe('API Keys', () => { error_details: [], }); expect(mockScopedClusterClient.asCurrentUser.security.invalidateApiKey).toHaveBeenCalledWith({ - body: { - ids: ['123'], - }, + ids: ['123'], }); }); }); @@ -736,9 +728,7 @@ describe('API Keys', () => { error_details: [], }); expect(mockClusterClient.asInternalUser.security.invalidateApiKey).toHaveBeenCalledWith({ - body: { - ids: ['123'], - }, + ids: ['123'], }); }); @@ -761,9 +751,7 @@ describe('API Keys', () => { error_details: [], }); expect(mockClusterClient.asInternalUser.security.invalidateApiKey).toHaveBeenCalledWith({ - body: { - ids: ['123'], - }, + ids: ['123'], }); }); }); @@ -804,24 +792,22 @@ describe('API Keys', () => { name: 'key-name', }); expect(mockScopedClusterClient.asCurrentUser.security.createApiKey).toHaveBeenCalledWith({ - body: { - name: 'key-name', - role_descriptors: { - synthetics_writer: { - applications: [ - { - application: 'kibana-.kibana', - privileges: ['feature_uptime.all'], - resources: ['*'], - }, - ], - cluster: ['manage'], - indices: [], - run_as: [], - }, + name: 'key-name', + role_descriptors: { + synthetics_writer: { + applications: [ + { + application: 'kibana-.kibana', + privileges: ['feature_uptime.all'], + resources: ['*'], + }, + ], + cluster: ['manage'], + indices: [], + run_as: [], }, - expiration: '1d', }, + expiration: '1d', }); }); diff --git a/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.ts b/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.ts index 054ab59fbd0bb..a1a7d417201cf 100644 --- a/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.ts +++ b/x-pack/platform/plugins/shared/security/server/authentication/api_keys/api_keys.ts @@ -98,11 +98,7 @@ export class APIKeys implements APIKeysType { `Testing if API Keys are enabled by attempting to invalidate a non-existant key: ${id}` ); try { - await this.clusterClient.asInternalUser.security.invalidateApiKey({ - body: { - ids: [id], - }, - }); + await this.clusterClient.asInternalUser.security.invalidateApiKey({ ids: [id] }); return true; } catch (e) { if (this.doesErrorIndicateAPIKeysAreDisabled(e)) { @@ -170,18 +166,16 @@ export class APIKeys implements APIKeysType { }); } else { result = await scopedClusterClient.asCurrentUser.security.createApiKey({ - body: { - name, - expiration, - metadata, - role_descriptors: isCreateRestAPIKeyParams(createParams) - ? createParams.role_descriptors - : this.parseRoleDescriptorsWithKibanaPrivileges( - createParams.kibana_role_descriptors, - this.kibanaFeatures, - false - ), - }, + name, + expiration, + metadata, + role_descriptors: isCreateRestAPIKeyParams(createParams) + ? createParams.role_descriptors + : this.parseRoleDescriptorsWithKibanaPrivileges( + createParams.kibana_role_descriptors, + this.kibanaFeatures, + false + ), }); } @@ -296,6 +290,7 @@ export class APIKeys implements APIKeysType { // User needs `manage_api_key` or `grant_api_key` privilege to use this API let result: GrantAPIKeyResult; try { + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 (client_authentication) result = await this.clusterClient.asInternalUser.security.grantApiKey({ body: params }); this.logger.debug('API key was granted successfully'); } catch (e) { @@ -321,9 +316,7 @@ export class APIKeys implements APIKeysType { try { // User needs `manage_api_key` privilege to use this API result = await this.clusterClient.asScoped(request).asCurrentUser.security.invalidateApiKey({ - body: { - ids: params.ids, - }, + ids: params.ids, }); this.logger.debug( `API keys by ids=[${params.ids.join(', ')}] was invalidated successfully as current user` @@ -356,9 +349,7 @@ export class APIKeys implements APIKeysType { try { // Internal user needs `cluster:admin/xpack/security/api_key/invalidate` privilege to use this API result = await this.clusterClient.asInternalUser.security.invalidateApiKey({ - body: { - ids: params.ids, - }, + ids: params.ids, }); this.logger.debug(`API keys by ids=[${params.ids.join(', ')}] was invalidated successfully`); } catch (e) { diff --git a/x-pack/platform/plugins/shared/security/server/authentication/providers/token.test.ts b/x-pack/platform/plugins/shared/security/server/authentication/providers/token.test.ts index f8ef97caf78a4..116cdd3d038d4 100644 --- a/x-pack/platform/plugins/shared/security/server/authentication/providers/token.test.ts +++ b/x-pack/platform/plugins/shared/security/server/authentication/providers/token.test.ts @@ -72,7 +72,8 @@ describe('TokenAuthenticationProvider', () => { expect(mockOptions.client.asScoped).not.toHaveBeenCalled(); expect(mockOptions.client.asInternalUser.security.getToken).toHaveBeenCalledTimes(1); expect(mockOptions.client.asInternalUser.security.getToken).toHaveBeenCalledWith({ - body: { grant_type: 'password', ...credentials }, + grant_type: 'password', + ...credentials, }); }); @@ -92,7 +93,8 @@ describe('TokenAuthenticationProvider', () => { expect(mockOptions.client.asScoped).not.toHaveBeenCalled(); expect(mockOptions.client.asInternalUser.security.getToken).toHaveBeenCalledTimes(1); expect(mockOptions.client.asInternalUser.security.getToken).toHaveBeenCalledWith({ - body: { grant_type: 'password', ...credentials }, + grant_type: 'password', + ...credentials, }); expect(request.headers).not.toHaveProperty('authorization'); diff --git a/x-pack/platform/plugins/shared/security/server/authentication/providers/token.ts b/x-pack/platform/plugins/shared/security/server/authentication/providers/token.ts index bc2ec0dd15a87..14b8986e15592 100644 --- a/x-pack/platform/plugins/shared/security/server/authentication/providers/token.ts +++ b/x-pack/platform/plugins/shared/security/server/authentication/providers/token.ts @@ -72,11 +72,9 @@ export class TokenAuthenticationProvider extends BaseAuthenticationProvider { refresh_token: refreshToken, authentication: authenticationInfo, } = await this.options.client.asInternalUser.security.getToken({ - body: { - grant_type: 'password', - username, - password, - }, + grant_type: 'password', + username, + password, }); this.logger.debug('Get token API request to Elasticsearch successful'); diff --git a/x-pack/platform/plugins/shared/security/server/authentication/tokens.test.ts b/x-pack/platform/plugins/shared/security/server/authentication/tokens.test.ts index 8269184a2dca8..ede62f58aed5b 100644 --- a/x-pack/platform/plugins/shared/security/server/authentication/tokens.test.ts +++ b/x-pack/platform/plugins/shared/security/server/authentication/tokens.test.ts @@ -82,7 +82,8 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.getToken).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.security.getToken).toHaveBeenCalledWith({ - body: { grant_type: 'refresh_token', refresh_token: refreshToken }, + grant_type: 'refresh_token', + refresh_token: refreshToken, }); }); @@ -96,7 +97,8 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.getToken).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.security.getToken).toHaveBeenCalledWith({ - body: { grant_type: 'refresh_token', refresh_token: refreshToken }, + grant_type: 'refresh_token', + refresh_token: refreshToken, }); }); @@ -119,7 +121,8 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.getToken).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.security.getToken).toHaveBeenCalledWith({ - body: { grant_type: 'refresh_token', refresh_token: refreshToken }, + grant_type: 'refresh_token', + refresh_token: refreshToken, }); }); }); @@ -147,7 +150,7 @@ describe('Tokens', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; mockElasticsearchClient.security.invalidateToken.mockImplementation((args: any) => { - if (args && args.body && args.body.token) { + if (args && args.token) { return Promise.reject(failureReason) as any; } @@ -160,10 +163,10 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(2); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { token: tokenPair.accessToken }, + token: tokenPair.accessToken, }); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { refresh_token: tokenPair.refreshToken }, + refresh_token: tokenPair.refreshToken, }); }); @@ -171,7 +174,7 @@ describe('Tokens', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; mockElasticsearchClient.security.invalidateToken.mockImplementation((args: any) => { - if (args && args.body && args.body.refresh_token) { + if (args && args.refresh_token) { return Promise.reject(failureReason) as any; } @@ -184,10 +187,10 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(2); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { token: tokenPair.accessToken }, + token: tokenPair.accessToken, }); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { refresh_token: tokenPair.refreshToken }, + refresh_token: tokenPair.refreshToken, }); }); } @@ -206,10 +209,10 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(2); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { token: tokenPair.accessToken }, + token: tokenPair.accessToken, }); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { refresh_token: tokenPair.refreshToken }, + refresh_token: tokenPair.refreshToken, }); }); @@ -227,7 +230,7 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { token: tokenPair.accessToken }, + token: tokenPair.accessToken, }); }); @@ -245,7 +248,7 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { refresh_token: tokenPair.refreshToken }, + refresh_token: tokenPair.refreshToken, }); }); @@ -270,10 +273,10 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(2); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { token: tokenPair.accessToken }, + token: tokenPair.accessToken, }); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { refresh_token: tokenPair.refreshToken }, + refresh_token: tokenPair.refreshToken, }); }); } @@ -292,10 +295,10 @@ describe('Tokens', () => { expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledTimes(2); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { token: tokenPair.accessToken }, + token: tokenPair.accessToken, }); expect(mockElasticsearchClient.security.invalidateToken).toHaveBeenCalledWith({ - body: { refresh_token: tokenPair.refreshToken }, + refresh_token: tokenPair.refreshToken, }); }); }); diff --git a/x-pack/platform/plugins/shared/security/server/authentication/tokens.ts b/x-pack/platform/plugins/shared/security/server/authentication/tokens.ts index 2cb644dd5caec..da0641f0517e4 100644 --- a/x-pack/platform/plugins/shared/security/server/authentication/tokens.ts +++ b/x-pack/platform/plugins/shared/security/server/authentication/tokens.ts @@ -60,10 +60,8 @@ export class Tokens { refresh_token: refreshToken, authentication: authenticationInfo, } = await this.options.client.security.getToken({ - body: { - grant_type: 'refresh_token', - refresh_token: existingRefreshToken, - }, + grant_type: 'refresh_token', + refresh_token: existingRefreshToken, }); this.logger.debug('Access token has been successfully refreshed.'); @@ -118,9 +116,7 @@ export class Tokens { let invalidatedTokensCount; try { invalidatedTokensCount = ( - await this.options.client.security.invalidateToken({ - body: { refresh_token: refreshToken }, - }) + await this.options.client.security.invalidateToken({ refresh_token: refreshToken }) ).invalidated_tokens; } catch (err) { this.logger.debug( @@ -152,9 +148,7 @@ export class Tokens { let invalidatedTokensCount; try { invalidatedTokensCount = ( - await this.options.client.security.invalidateToken({ - body: { token: accessToken }, - }) + await this.options.client.security.invalidateToken({ token: accessToken }) ).invalidated_tokens; } catch (err) { this.logger.debug( diff --git a/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.test.ts b/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.test.ts index c4da8a95ae46f..49338c84317ca 100644 --- a/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.test.ts +++ b/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.test.ts @@ -72,24 +72,22 @@ describe('#checkPrivilegesWithRequest.atSpace', () => { expect(mockClusterClient.asScoped).toHaveBeenCalledWith(request); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - cluster: options.elasticsearchPrivileges?.cluster, - index: expectedIndexPrivilegePayload, - application: [ - { - application, - resources: [`space:${options.spaceId}`], - privileges: options.kibanaPrivileges - ? uniq([ - mockActions.login, - ...(Array.isArray(options.kibanaPrivileges) - ? options.kibanaPrivileges - : [options.kibanaPrivileges]), - ]) - : [mockActions.login], - }, - ], - }, + cluster: options.elasticsearchPrivileges?.cluster, + index: expectedIndexPrivilegePayload, + application: [ + { + application, + resources: [`space:${options.spaceId}`], + privileges: options.kibanaPrivileges + ? uniq([ + mockActions.login, + ...(Array.isArray(options.kibanaPrivileges) + ? options.kibanaPrivileges + : [options.kibanaPrivileges]), + ]) + : [mockActions.login], + }, + ], }); if (errorThrown) { @@ -860,16 +858,14 @@ describe('#checkPrivilegesWithRequest.atSpace', () => { await checkPrivileges.atSpace('space_1', {}, { requireLoginAction: false }); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - index: [], - application: [ - { - application, - resources: [`space:space_1`], - privileges: [], - }, - ], - }, + index: [], + application: [ + { + application, + resources: [`space:space_1`], + privileges: [], + }, + ], }); }); }); @@ -915,24 +911,22 @@ describe('#checkPrivilegesWithRequest.atSpaces', () => { expect(mockClusterClient.asScoped).toHaveBeenCalledWith(request); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - cluster: options.elasticsearchPrivileges?.cluster, - index: expectedIndexPrivilegePayload, - application: [ - { - application, - resources: options.spaceIds.map((spaceId) => `space:${spaceId}`), - privileges: options.kibanaPrivileges - ? uniq([ - mockActions.login, - ...(Array.isArray(options.kibanaPrivileges) - ? options.kibanaPrivileges - : [options.kibanaPrivileges]), - ]) - : [mockActions.login], - }, - ], - }, + cluster: options.elasticsearchPrivileges?.cluster, + index: expectedIndexPrivilegePayload, + application: [ + { + application, + resources: options.spaceIds.map((spaceId) => `space:${spaceId}`), + privileges: options.kibanaPrivileges + ? uniq([ + mockActions.login, + ...(Array.isArray(options.kibanaPrivileges) + ? options.kibanaPrivileges + : [options.kibanaPrivileges]), + ]) + : [mockActions.login], + }, + ], }); if (errorThrown) { @@ -2034,16 +2028,14 @@ describe('#checkPrivilegesWithRequest.atSpaces', () => { await checkPrivileges.atSpaces(['space_1'], {}, { requireLoginAction: false }); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - index: [], - application: [ - { - application, - resources: [`space:space_1`], - privileges: [], - }, - ], - }, + index: [], + application: [ + { + application, + resources: [`space:space_1`], + privileges: [], + }, + ], }); }); }); @@ -2088,24 +2080,22 @@ describe('#checkPrivilegesWithRequest.globally', () => { expect(mockClusterClient.asScoped).toHaveBeenCalledWith(request); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - cluster: options.elasticsearchPrivileges?.cluster, - index: expectedIndexPrivilegePayload, - application: [ - { - application, - resources: [GLOBAL_RESOURCE], - privileges: options.kibanaPrivileges - ? uniq([ - mockActions.login, - ...(Array.isArray(options.kibanaPrivileges) - ? options.kibanaPrivileges - : [options.kibanaPrivileges]), - ]) - : [mockActions.login], - }, - ], - }, + cluster: options.elasticsearchPrivileges?.cluster, + index: expectedIndexPrivilegePayload, + application: [ + { + application, + resources: [GLOBAL_RESOURCE], + privileges: options.kibanaPrivileges + ? uniq([ + mockActions.login, + ...(Array.isArray(options.kibanaPrivileges) + ? options.kibanaPrivileges + : [options.kibanaPrivileges]), + ]) + : [mockActions.login], + }, + ], }); if (errorThrown) { @@ -2886,16 +2876,14 @@ describe('#checkPrivilegesWithRequest.globally', () => { await checkPrivileges.globally({}, { requireLoginAction: false }); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - index: [], - application: [ - { - application, - resources: [GLOBAL_RESOURCE], - privileges: [], - }, - ], - }, + index: [], + application: [ + { + application, + resources: [GLOBAL_RESOURCE], + privileges: [], + }, + ], }); }); }); diff --git a/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.ts b/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.ts index 310b79f362824..ad1c4d1d406d8 100644 --- a/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.ts +++ b/x-pack/platform/plugins/shared/security/server/authorization/check_privileges.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { pick, transform, uniq } from 'lodash'; import type { IClusterClient, KibanaRequest } from '@kbn/core/server'; @@ -109,16 +109,14 @@ export function checkPrivilegesFactory( const clusterClient = await getClusterClient(); const body = await clusterClient.asScoped(request).asCurrentUser.security.hasPrivileges({ - body: { - cluster: privileges.elasticsearch?.cluster as estypes.SecurityClusterPrivilege[], - index: Object.entries(privileges.elasticsearch?.index ?? {}).map( - ([name, indexPrivileges]) => ({ - names: [name], - privileges: indexPrivileges as estypes.SecurityIndexPrivilege[], - }) - ), - application: [applicationPrivilegesCheck], - }, + cluster: privileges.elasticsearch?.cluster as estypes.SecurityClusterPrivilege[], + index: Object.entries(privileges.elasticsearch?.index ?? {}).map( + ([name, indexPrivileges]) => ({ + names: [name], + privileges: indexPrivileges as estypes.SecurityIndexPrivilege[], + }) + ), + application: [applicationPrivilegesCheck], }); const hasPrivilegesResponse: HasPrivilegesResponse = body; diff --git a/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.test.ts b/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.test.ts index 16f39383997e9..3b280eb488ba3 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.test.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.test.ts @@ -133,7 +133,7 @@ describe('Invalidate API keys', () => { isAdmin: true, }, asserts: { - apiArguments: [{ body: { ids: ['si8If24B1bKsmSLTAhJV'] } }], + apiArguments: [{ ids: ['si8If24B1bKsmSLTAhJV'] }], statusCode: 200, result: { itemsInvalidated: [], @@ -157,7 +157,7 @@ describe('Invalidate API keys', () => { isAdmin: true, }, asserts: { - apiArguments: [{ body: { ids: ['si8If24B1bKsmSLTAhJV'] } }], + apiArguments: [{ ids: ['si8If24B1bKsmSLTAhJV'] }], statusCode: 200, result: { itemsInvalidated: [{ id: 'si8If24B1bKsmSLTAhJV', name: 'my-api-key' }], @@ -173,7 +173,7 @@ describe('Invalidate API keys', () => { isAdmin: false, }, asserts: { - apiArguments: [{ body: { ids: ['si8If24B1bKsmSLTAhJV'], owner: true } }], + apiArguments: [{ ids: ['si8If24B1bKsmSLTAhJV'], owner: true }], statusCode: 200, result: { itemsInvalidated: [{ id: 'si8If24B1bKsmSLTAhJV', name: 'my-api-key' }], @@ -197,10 +197,7 @@ describe('Invalidate API keys', () => { isAdmin: true, }, asserts: { - apiArguments: [ - { body: { ids: ['si8If24B1bKsmSLTAhJV'] } }, - { body: { ids: ['ab8If24B1bKsmSLTAhNC'] } }, - ], + apiArguments: [{ ids: ['si8If24B1bKsmSLTAhJV'] }, { ids: ['ab8If24B1bKsmSLTAhNC'] }], statusCode: 200, result: { itemsInvalidated: [{ id: 'si8If24B1bKsmSLTAhJV', name: 'my-api-key1' }], diff --git a/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.ts b/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.ts index f2d72185d0b1c..6f8f6aca17048 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/api_keys/invalidate.ts @@ -48,9 +48,7 @@ export function defineInvalidateApiKeysRoutes({ router }: RouteDefinitionParams) } // Send the request to invalidate the API key and return an error if it could not be deleted. - await esClient.asCurrentUser.security.invalidateApiKey({ - body, - }); + await esClient.asCurrentUser.security.invalidateApiKey(body); return { key, error: undefined }; } catch (error) { return { key, error: wrapError(error) }; diff --git a/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.test.ts b/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.test.ts index d3a37ed879320..c73e3190eac74 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.test.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.test.ts @@ -6,7 +6,7 @@ */ import { errors } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { RequestHandler, RouteConfig } from '@kbn/core/server'; import { kibanaResponseFactory } from '@kbn/core/server'; @@ -97,8 +97,8 @@ describe('Kibana user deprecation routes', () => { expect( mockContext.core.elasticsearch.client.asCurrentUser.security.putUser ).toHaveBeenCalledWith({ + ...createMockUser({ username: 'userA', roles: ['roleA', 'kibana_admin'] }), username: 'userA', - body: createMockUser({ username: 'userA', roles: ['roleA', 'kibana_admin'] }), }); }); @@ -138,20 +138,20 @@ describe('Kibana user deprecation routes', () => { expect( mockContext.core.elasticsearch.client.asCurrentUser.security.putUser ).toHaveBeenCalledWith({ + ...createMockUser({ username: 'userB', roles: ['roleB', 'kibana_admin'] }), username: 'userB', - body: createMockUser({ username: 'userB', roles: ['roleB', 'kibana_admin'] }), }); expect( mockContext.core.elasticsearch.client.asCurrentUser.security.putUser ).toHaveBeenCalledWith({ + ...createMockUser({ username: 'userD', roles: ['kibana_admin'] }), username: 'userD', - body: createMockUser({ username: 'userD', roles: ['kibana_admin'] }), }); expect( mockContext.core.elasticsearch.client.asCurrentUser.security.putUser ).toHaveBeenCalledWith({ + ...createMockUser({ username: 'userE', roles: ['kibana_admin', 'roleE'] }), username: 'userE', - body: createMockUser({ username: 'userE', roles: ['kibana_admin', 'roleE'] }), }); }); }); @@ -212,7 +212,7 @@ describe('Kibana user deprecation routes', () => { mockContext.core.elasticsearch.client.asCurrentUser.security.putRoleMapping ).toHaveBeenCalledWith({ name: 'mappingA', - body: createMockRoleMapping({ roles: ['roleA', 'kibana_admin'] }), + ...createMockRoleMapping({ roles: ['roleA', 'kibana_admin'] }), }); }); @@ -250,19 +250,19 @@ describe('Kibana user deprecation routes', () => { mockContext.core.elasticsearch.client.asCurrentUser.security.putRoleMapping ).toHaveBeenCalledWith({ name: 'mappingB', - body: createMockRoleMapping({ roles: ['roleB', 'kibana_admin'] }), + ...createMockRoleMapping({ roles: ['roleB', 'kibana_admin'] }), }); expect( mockContext.core.elasticsearch.client.asCurrentUser.security.putRoleMapping ).toHaveBeenCalledWith({ name: 'mappingD', - body: createMockRoleMapping({ roles: ['kibana_admin'] }), + ...createMockRoleMapping({ roles: ['kibana_admin'] }), }); expect( mockContext.core.elasticsearch.client.asCurrentUser.security.putRoleMapping ).toHaveBeenCalledWith({ name: 'mappingE', - body: createMockRoleMapping({ roles: ['kibana_admin', 'roleE'] }), + ...createMockRoleMapping({ roles: ['kibana_admin', 'roleE'] }), }); }); }); diff --git a/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.ts b/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.ts index b7c9c5729392d..48464c9cc95cd 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/deprecations/kibana_user_role.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { RouteDefinitionParams } from '..'; import { KIBANA_ADMIN_ROLE_NAME, KIBANA_USER_ROLE_NAME } from '../../deprecations'; @@ -74,8 +74,8 @@ export function defineKibanaUserRoleDeprecationRoutes({ router, logger }: RouteD try { await esClient.asCurrentUser.security.putUser({ - username: userToUpdate.username, - body: { ...userToUpdate, roles }, + ...userToUpdate, + roles, }); } catch (err) { logger.error( @@ -136,7 +136,8 @@ export function defineKibanaUserRoleDeprecationRoutes({ router, logger }: RouteD try { await esClient.asCurrentUser.security.putRoleMapping({ name: mappingNameToUpdate, - body: { ...mappingToUpdate, roles }, + ...mappingToUpdate, + roles, }); } catch (err) { logger.error( diff --git a/x-pack/platform/plugins/shared/security/server/routes/feature_check/feature_check.ts b/x-pack/platform/plugins/shared/security/server/routes/feature_check/feature_check.ts index 6f4cd5b4b2654..31759deb83511 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/feature_check/feature_check.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/feature_check/feature_check.ts @@ -55,7 +55,7 @@ export function defineSecurityFeatureCheckRoute({ router, logger }: RouteDefinit const esClient = (await context.core).elasticsearch.client; const { has_all_requested: canReadSecurity } = await esClient.asCurrentUser.security.hasPrivileges({ - body: { cluster: ['read_security'] }, + cluster: ['read_security'], }); if (!canReadSecurity) { diff --git a/x-pack/platform/plugins/shared/security/server/routes/users/change_password.test.ts b/x-pack/platform/plugins/shared/security/server/routes/users/change_password.test.ts index b53642e96af1e..e7f565f32961e 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/users/change_password.test.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/users/change_password.test.ts @@ -40,10 +40,7 @@ describe('Change password', () => { ).toHaveBeenCalledTimes(1); expect( mockCoreContext.elasticsearch.client.asCurrentUser.security.changePassword - ).toHaveBeenCalledWith( - { username, body: { password: 'new-password' } }, - headers && { headers } - ); + ).toHaveBeenCalledWith({ username, password: 'new-password' }, headers && { headers }); } beforeEach(() => { diff --git a/x-pack/platform/plugins/shared/security/server/routes/users/change_password.ts b/x-pack/platform/plugins/shared/security/server/routes/users/change_password.ts index 964d3d6fe888b..72db3d80130d2 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/users/change_password.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/users/change_password.ts @@ -67,7 +67,7 @@ export function defineChangeUserPasswordRoutes({ try { const esClient = (await context.core).elasticsearch.client; await esClient.asCurrentUser.security.changePassword( - { username, body: { password: newPassword } }, + { username, password: newPassword }, options ); } catch (error) { diff --git a/x-pack/platform/plugins/shared/security/server/routes/users/create_or_update.ts b/x-pack/platform/plugins/shared/security/server/routes/users/create_or_update.ts index c6c0bcbc48415..3b00cd192a9a1 100644 --- a/x-pack/platform/plugins/shared/security/server/routes/users/create_or_update.ts +++ b/x-pack/platform/plugins/shared/security/server/routes/users/create_or_update.ts @@ -38,8 +38,8 @@ export function defineCreateOrUpdateUserRoutes({ router }: RouteDefinitionParams try { const esClient = (await context.core).elasticsearch.client; await esClient.asCurrentUser.security.putUser({ + ...request.body, username: request.params.username, - body: request.body, }); return response.ok({ body: request.body }); diff --git a/x-pack/platform/plugins/shared/security/server/session_management/session_index.test.ts b/x-pack/platform/plugins/shared/security/server/session_management/session_index.test.ts index bf20ade0b2fec..c21fd4c071c08 100644 --- a/x-pack/platform/plugins/shared/security/server/session_management/session_index.test.ts +++ b/x-pack/platform/plugins/shared/security/server/session_management/session_index.test.ts @@ -340,7 +340,7 @@ describe('Session index', () => { expect(mockElasticsearchClient.indices.putMapping).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.indices.putMapping).toHaveBeenCalledWith({ index: aliasName, - ...getSessionIndexSettings({ indexName, aliasName }).mappings, + body: getSessionIndexSettings({ indexName, aliasName }).mappings, }); }); @@ -367,7 +367,7 @@ describe('Session index', () => { expect(mockElasticsearchClient.indices.putMapping).toHaveBeenCalledTimes(1); expect(mockElasticsearchClient.indices.putMapping).toHaveBeenCalledWith({ index: aliasName, - ...getSessionIndexSettings({ indexName, aliasName }).mappings, + body: getSessionIndexSettings({ indexName, aliasName }).mappings, }); }); @@ -1578,7 +1578,7 @@ describe('Session index', () => { { id: sid, index: aliasName, - body: sessionValue, + document: sessionValue, refresh: false, require_alias: true, }, @@ -1589,7 +1589,7 @@ describe('Session index', () => { { id: sid, index: aliasName, - body: sessionValue, + document: sessionValue, refresh: false, require_alias: true, }, @@ -1633,7 +1633,7 @@ describe('Session index', () => { { id: sid, index: aliasName, - body: sessionValue, + document: sessionValue, refresh: false, require_alias: true, }, @@ -1867,7 +1867,7 @@ describe('Session index', () => { expect(mockElasticsearchClient.deleteByQuery).toHaveBeenCalledWith({ index: aliasName, refresh: false, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); }); @@ -1891,7 +1891,7 @@ describe('Session index', () => { expect(mockElasticsearchClient.deleteByQuery).toHaveBeenCalledWith({ index: aliasName, refresh: false, - body: { query: { bool: { must: [{ term: { 'provider.type': 'basic' } }] } } }, + query: { bool: { must: [{ term: { 'provider.type': 'basic' } }] } }, }); }); @@ -1907,14 +1907,9 @@ describe('Session index', () => { expect(mockElasticsearchClient.deleteByQuery).toHaveBeenCalledWith({ index: aliasName, refresh: false, - body: { - query: { - bool: { - must: [ - { term: { 'provider.type': 'basic' } }, - { term: { 'provider.name': 'basic1' } }, - ], - }, + query: { + bool: { + must: [{ term: { 'provider.type': 'basic' } }, { term: { 'provider.name': 'basic1' } }], }, }, }); @@ -1932,14 +1927,9 @@ describe('Session index', () => { expect(mockElasticsearchClient.deleteByQuery).toHaveBeenCalledWith({ index: aliasName, refresh: false, - body: { - query: { - bool: { - must: [ - { term: { 'provider.type': 'basic' } }, - { term: { usernameHash: 'some-hash' } }, - ], - }, + query: { + bool: { + must: [{ term: { 'provider.type': 'basic' } }, { term: { usernameHash: 'some-hash' } }], }, }, }); @@ -1957,15 +1947,13 @@ describe('Session index', () => { expect(mockElasticsearchClient.deleteByQuery).toHaveBeenCalledWith({ index: aliasName, refresh: false, - body: { - query: { - bool: { - must: [ - { term: { 'provider.type': 'basic' } }, - { term: { 'provider.name': 'basic1' } }, - { term: { usernameHash: 'some-hash' } }, - ], - }, + query: { + bool: { + must: [ + { term: { 'provider.type': 'basic' } }, + { term: { 'provider.name': 'basic1' } }, + { term: { usernameHash: 'some-hash' } }, + ], }, }, }); diff --git a/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts b/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts index b916b3ce874f9..0945a157e15cd 100644 --- a/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts +++ b/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts @@ -381,7 +381,7 @@ export class SessionIndex { const response = await this.options.elasticsearchClient.deleteByQuery({ index: this.aliasName, refresh: false, - body: { query: deleteQuery }, + query: deleteQuery, }); return response.deleted as number; } catch (err) { @@ -762,7 +762,8 @@ export class SessionIndex { try { await this.options.elasticsearchClient.indices.putMapping({ index: this.aliasName, - ...sessionIndexSettings.mappings, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 + body: sessionIndexSettings.mappings, }); this.options.logger.debug('Successfully updated session index mappings.'); } catch (err) { @@ -783,7 +784,7 @@ export class SessionIndex { id: sid, // We write to the alias for `create` operations so that we can prevent index auto-creation in the event it is missing. index: this.aliasName, - body: sessionValueToStore, + document: sessionValueToStore, refresh: false, require_alias: true, } as CreateRequest, diff --git a/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.test.ts b/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.test.ts index 47644cfc05705..5bc9b05183b80 100644 --- a/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.test.ts +++ b/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.test.ts @@ -164,17 +164,15 @@ describe('with a basic license', () => { usageData = await collector.fetch(getMockFetchContext(esClient)); expect(esClient.search).toHaveBeenCalledWith({ - body: { - aggs: { - disabledFeatures: { - terms: { field: 'space.disabledFeatures', include: ['feature1', 'feature2'], size: 2 }, - }, - solution: { terms: { field: 'space.solution', missing: 'unset', size: 5 } }, + aggs: { + disabledFeatures: { + terms: { field: 'space.disabledFeatures', include: ['feature1', 'feature2'], size: 2 }, }, - query: { term: { type: { value: 'space' } } }, - size: 0, - track_total_hits: true, + solution: { terms: { field: 'space.solution', missing: 'unset', size: 5 } }, }, + query: { term: { type: { value: 'space' } } }, + size: 0, + track_total_hits: true, index: kibanaIndex, }); }); diff --git a/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.ts b/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.ts index b57ba097ab6a4..d15ff402441d1 100644 --- a/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.ts +++ b/x-pack/platform/plugins/shared/spaces/server/usage_collection/spaces_usage_collector.ts @@ -57,33 +57,31 @@ async function getSpacesUsage( const resp = (await esClient.search({ index: kibanaIndex, - body: { - track_total_hits: true, - query: { - term: { - type: { - value: 'space', - }, + track_total_hits: true, + query: { + term: { + type: { + value: 'space', }, }, - aggs: { - disabledFeatures: { - terms: { - field: 'space.disabledFeatures', - include: knownFeatureIds, - size: knownFeatureIds.length, - }, + }, + aggs: { + disabledFeatures: { + terms: { + field: 'space.disabledFeatures', + include: knownFeatureIds, + size: knownFeatureIds.length, }, - solution: { - terms: { - field: 'space.solution', - size: knownSolutions.length, - missing: 'unset', - }, + }, + solution: { + terms: { + field: 'space.solution', + size: knownSolutions.length, + missing: 'unset', }, }, - size: 0, }, + size: 0, })) as SpacesAggregationResponse; const { hits, aggregations } = resp; diff --git a/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.test.ts b/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.test.ts index 0aa94e319b430..ec714e05194c2 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.test.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.test.ts @@ -30,44 +30,42 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: false, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'asc', }, - }, - ], + ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'asc', + }, + }, + ], }); }); @@ -79,44 +77,42 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: false, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'asc', }, - }, - ], + ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'asc', + }, + }, + ], }); }); @@ -129,45 +125,43 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: false, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'asc', }, - }, - ], - search_after: [sortId], + ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'asc', + }, + }, + ], + search_after: [sortId], }); }); @@ -180,45 +174,43 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: false, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'asc', }, - }, - ], - search_after: [sortId], + ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'asc', + }, + }, + ], + search_after: [sortId], }); }); @@ -236,51 +228,49 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: false, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - aggs: { - tags: { - terms: { - field: 'tag', }, - }, + ], }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'asc', - }, + }, + aggs: { + tags: { + terms: { + field: 'tag', }, - ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'asc', + }, + }, + ], }); }); @@ -292,44 +282,42 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: false, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'desc', }, - }, - ], + ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'desc', + }, + }, + ], }); }); @@ -341,44 +329,42 @@ describe('buildSortedEventsQuery', () => { size: 100, ignore_unavailable: true, track_total_hits: true, - body: { - docvalue_fields: [ - { - field: 'timefield', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - {}, - { - bool: { - filter: [ - { - range: { - timefield: { - gte: '2021-01-01T00:00:10.123Z', - lte: '2021-01-23T12:00:50.321Z', - format: 'strict_date_optional_time', - }, + docvalue_fields: [ + { + field: 'timefield', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + {}, + { + bool: { + filter: [ + { + range: { + timefield: { + gte: '2021-01-01T00:00:10.123Z', + lte: '2021-01-23T12:00:50.321Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - timefield: { - format: 'strict_date_optional_time||epoch_millis', - order: 'asc', }, - }, - ], + ], + }, }, + sort: [ + { + timefield: { + format: 'strict_date_optional_time||epoch_millis', + order: 'asc', + }, + }, + ], }); }); }); diff --git a/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.ts b/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.ts index 5253fb8eb74ee..bdfd2370a1bf4 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/common/build_sorted_events_query.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ESSearchRequest } from '@kbn/es-types'; interface BuildSortedEventsQueryOpts { @@ -68,23 +68,21 @@ export const buildSortedEventsQuery = ({ size, ignore_unavailable: true, track_total_hits: track_total_hits ?? false, - body: { - docvalue_fields: docFields, - query: { - bool: { - filter: [...filterWithTime], - }, + docvalue_fields: docFields, + query: { + bool: { + filter: [...filterWithTime], }, - ...(aggs ? { aggs } : {}), - sort: [ - { - [sortField]: { - order: sortOrder ?? 'asc', - format: 'strict_date_optional_time||epoch_millis', - }, - }, - ], }, + ...(aggs ? { aggs } : {}), + sort: [ + { + [sortField]: { + order: sortOrder ?? 'asc', + format: 'strict_date_optional_time||epoch_millis', + }, + }, + ], ...(runtime_mappings ? { runtime_mappings } : {}), ...(fields ? { fields } : {}), ...(_source != null ? { _source } : {}), @@ -93,10 +91,7 @@ export const buildSortedEventsQuery = ({ if (searchAfterSortId) { return { ...searchQuery, - body: { - ...searchQuery.body, - search_after: [searchAfterSortId], - }, + search_after: [searchAfterSortId], } as ESSearchRequest; } return searchQuery as ESSearchRequest; diff --git a/x-pack/platform/plugins/shared/stack_alerts/public/rule_types/es_query/util.ts b/x-pack/platform/plugins/shared/stack_alerts/public/rule_types/es_query/util.ts index 7ca42220c3ebf..70b60a5c8c36e 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/public/rule_types/es_query/util.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/public/rule_types/es_query/util.ts @@ -8,7 +8,7 @@ import { FieldSpec } from '@kbn/data-views-plugin/common'; import { useKibana } from '@kbn/triggers-actions-ui-plugin/public'; import { FieldOption, NORMALIZED_FIELD_TYPES } from '@kbn/triggers-actions-ui-plugin/public/common'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EsQueryRuleParams, SearchType } from './types'; export const isSearchSourceRule = ( diff --git a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/action_context.ts b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/action_context.ts index f0955b0f49ffd..e70241e84651e 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/action_context.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/action_context.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { AlertInstanceContext } from '@kbn/alerting-plugin/server'; import type { EsQueryRuleParams } from '@kbn/response-ops-rule-params/es_query'; import { Comparator } from '../../../common/comparator_types'; diff --git a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/lib/fetch_es_query.test.ts b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/lib/fetch_es_query.test.ts index c0a4e272a1c26..f499db21537d5 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/lib/fetch_es_query.test.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/lib/fetch_es_query.test.ts @@ -75,73 +75,71 @@ describe('fetchEsQuery', () => { expect(scopedClusterClientMock.asCurrentUser.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: {}, - docvalue_fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - { - bool: { - filter: [ - { - match_all: {}, - }, - { - bool: { - must_not: [ - { - bool: { - filter: [ - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - lte: '2020-02-09T23:15:41.941Z', - }, + aggs: {}, + docvalue_fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + { + bool: { + filter: [ + { + match_all: {}, + }, + { + bool: { + must_not: [ + { + bool: { + filter: [ + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + lte: '2020-02-09T23:15:41.941Z', }, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: date, - lte: date, - }, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: date, + lte: date, }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - '@timestamp': { - format: 'strict_date_optional_time||epoch_millis', - order: 'desc', }, - }, - ], + ], + }, }, + sort: [ + { + '@timestamp': { + format: 'strict_date_optional_time||epoch_millis', + order: 'desc', + }, + }, + ], ignore_unavailable: true, index: ['test-index'], size: 100, @@ -169,47 +167,45 @@ describe('fetchEsQuery', () => { expect(scopedClusterClientMock.asCurrentUser.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: {}, - docvalue_fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - { - match_all: {}, - }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: date, - lte: date, - }, + aggs: {}, + docvalue_fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + { + match_all: {}, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: date, + lte: date, }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - '@timestamp': { - format: 'strict_date_optional_time||epoch_millis', - order: 'desc', }, - }, - ], + ], + }, }, + sort: [ + { + '@timestamp': { + format: 'strict_date_optional_time||epoch_millis', + order: 'desc', + }, + }, + ], ignore_unavailable: true, index: ['test-index'], size: 100, @@ -237,47 +233,45 @@ describe('fetchEsQuery', () => { expect(scopedClusterClientMock.asCurrentUser.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: {}, - docvalue_fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - { - match_all: {}, - }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: date, - lte: date, - }, + aggs: {}, + docvalue_fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + { + match_all: {}, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: date, + lte: date, }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - '@timestamp': { - format: 'strict_date_optional_time||epoch_millis', - order: 'desc', }, - }, - ], + ], + }, }, + sort: [ + { + '@timestamp': { + format: 'strict_date_optional_time||epoch_millis', + order: 'desc', + }, + }, + ], ignore_unavailable: true, index: ['test-index'], size: 100, @@ -305,74 +299,72 @@ describe('fetchEsQuery', () => { expect(scopedClusterClientMock.asCurrentUser.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - aggs: { - conditionSelector: { - bucket_selector: { - buckets_path: { - compareValue: '_count', - }, - script: 'params.compareValue < 0L', - }, - }, - topHitsAgg: { - top_hits: { - size: 100, + aggs: { + groupAgg: { + aggs: { + conditionSelector: { + bucket_selector: { + buckets_path: { + compareValue: '_count', }, + script: 'params.compareValue < 0L', }, }, - terms: { - field: 'host.name', - size: 10, + topHitsAgg: { + top_hits: { + size: 100, + }, }, }, - groupAggCount: { - stats_bucket: { - buckets_path: 'groupAgg._count', - }, + terms: { + field: 'host.name', + size: 10, }, }, - docvalue_fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', + groupAggCount: { + stats_bucket: { + buckets_path: 'groupAgg._count', }, - ], - query: { - bool: { - filter: [ - { - match_all: {}, - }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: date, - lte: date, - }, + }, + }, + docvalue_fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + { + match_all: {}, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: date, + lte: date, }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - '@timestamp': { - format: 'strict_date_optional_time||epoch_millis', - order: 'desc', }, - }, - ], + ], + }, }, + sort: [ + { + '@timestamp': { + format: 'strict_date_optional_time||epoch_millis', + order: 'desc', + }, + }, + ], ignore_unavailable: true, index: ['test-index'], size: 0, @@ -407,74 +399,72 @@ describe('fetchEsQuery', () => { expect(scopedClusterClientMock.asCurrentUser.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - aggs: { - conditionSelector: { - bucket_selector: { - buckets_path: { - compareValue: '_count', - }, - script: 'params.compareValue < 0L', - }, - }, - topHitsAgg: { - top_hits: { - size: 100, + aggs: { + groupAgg: { + aggs: { + conditionSelector: { + bucket_selector: { + buckets_path: { + compareValue: '_count', }, + script: 'params.compareValue < 0L', }, }, - terms: { - field: 'host.name', - size: 10, + topHitsAgg: { + top_hits: { + size: 100, + }, }, }, - groupAggCount: { - stats_bucket: { - buckets_path: 'groupAgg._count', - }, + terms: { + field: 'host.name', + size: 10, }, }, - docvalue_fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', + groupAggCount: { + stats_bucket: { + buckets_path: 'groupAgg._count', }, - ], - query: { - bool: { - filter: [ - { - match_all: {}, - }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: date, - lte: date, - }, + }, + }, + docvalue_fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + { + match_all: {}, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: date, + lte: date, }, }, - ], - }, + }, + ], }, - ], - }, - }, - sort: [ - { - '@timestamp': { - format: 'strict_date_optional_time||epoch_millis', - order: 'desc', }, - }, - ], + ], + }, }, + sort: [ + { + '@timestamp': { + format: 'strict_date_optional_time||epoch_millis', + order: 'desc', + }, + }, + ], ignore_unavailable: true, index: ['test-index'], size: 0, diff --git a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/util.ts b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/util.ts index c2af56fd91da1..78a0ec2ab3173 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/util.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/es_query/util.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import { SearchResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { EsQueryRuleParams } from '@kbn/response-ops-rule-params/es_query'; import { OnlyEsQueryRuleParams } from './types'; diff --git a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/es_query_builder.ts b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/es_query_builder.ts index a456782ea37b1..565a545e25ea3 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/es_query_builder.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/es_query_builder.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; import { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { OTHER_CATEGORY } from '../constants'; import { getQueryDsl } from './get_query_dsl'; import type { GeoContainmentRuleParams } from '../types'; @@ -38,81 +38,79 @@ export async function executeEsQuery( const esQuery = { index, - body: { - size: 0, // do not fetch hits - aggs: { - shapes: { - filters: { - other_bucket_key: OTHER_CATEGORY, - filters: shapesFilters, - }, - aggs: { - entitySplit: { - terms: { - size: MAX_BUCKETS_LIMIT / ((Object.keys(shapesFilters).length || 1) * 2), - field: entity, - }, - aggs: { - entityHits: { - top_hits: { - size: 1, - sort: [ - { - [dateField]: { - order: 'desc', - }, - }, - ], - fields: [ - entity, - { - field: dateField, - format: 'strict_date_optional_time', - }, - { - field: geoField, - format: 'wkt', + size: 0, // do not fetch hits + aggs: { + shapes: { + filters: { + other_bucket_key: OTHER_CATEGORY, + filters: shapesFilters as estypes.AggregationsBuckets, + }, + aggs: { + entitySplit: { + terms: { + size: MAX_BUCKETS_LIMIT / ((Object.keys(shapesFilters).length || 1) * 2), + field: entity, + }, + aggs: { + entityHits: { + top_hits: { + size: 1, + sort: [ + { + [dateField]: { + order: 'desc' as const, }, - ], - _source: false, - }, + }, + ], + fields: [ + entity, + { + field: dateField, + format: 'strict_date_optional_time', + }, + { + field: geoField, + format: 'wkt', + }, + ], + _source: false, }, }, }, }, }, }, - query: esFormattedQuery - ? esFormattedQuery - : { - bool: { - must: [], - filter: [ - { - match_all: {}, - }, - { - range: { - [dateField]: { - ...(gteDateTime ? { gte: gteDateTime } : {}), - lt: ltDateTime, // 'less than' to prevent overlap between intervals - format: 'strict_date_optional_time', - }, + }, + query: esFormattedQuery + ? esFormattedQuery + : { + bool: { + must: [], + filter: [ + { + match_all: {}, + }, + { + range: { + [dateField]: { + ...(gteDateTime ? { gte: gteDateTime } : {}), + lt: ltDateTime, // 'less than' to prevent overlap between intervals + format: 'strict_date_optional_time', }, }, - ], - should: [], - must_not: [], - }, + }, + ], + should: [], + must_not: [], }, - stored_fields: ['*'], - docvalue_fields: [ - { - field: dateField, - format: 'date_time', }, - ], - }, + stored_fields: ['*'], + docvalue_fields: [ + { + field: dateField, + format: 'date_time', + }, + ], }; try { diff --git a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.ts b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.ts index e2626b565dcda..9e991edab5dbf 100644 --- a/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.ts +++ b/x-pack/platform/plugins/shared/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.ts @@ -55,12 +55,10 @@ export async function getShapeFilters( try { boundaryData = await esClient.search>({ index: boundaryIndexTitle, - body: { - size: MAX_SHAPES_QUERY_SIZE, - _source: false, - fields: boundaryNameField ? [boundaryNameField] : [], - ...(boundaryIndexQuery ? { query: getQueryDsl(boundaryIndexQuery) } : {}), - }, + size: MAX_SHAPES_QUERY_SIZE, + _source: false, + fields: boundaryNameField ? [boundaryNameField] : [], + ...(boundaryIndexQuery ? { query: getQueryDsl(boundaryIndexQuery) } : {}), }); } catch (e) { throw new Error( diff --git a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.test.ts b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.test.ts index 5b7353ef58291..2ca14b411e7f4 100644 --- a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.test.ts +++ b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { validateConfig, validateParams } from '@kbn/actions-plugin/server/lib'; import { ConnectorUsageCollector } from '@kbn/actions-plugin/server/types'; import { actionsMock } from '@kbn/actions-plugin/server/mocks'; diff --git a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.ts b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.ts index 9dd6a4c71ae21..02533146813f1 100644 --- a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.ts +++ b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/es_index/index.ts @@ -23,10 +23,7 @@ import { UptimeConnectorFeatureId, SecurityConnectorFeatureId, } from '@kbn/actions-plugin/common'; -import type { - BulkOperationType, - BulkResponseItem, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { BulkOperationType, BulkResponseItem } from '@elastic/elasticsearch/lib/api/types'; export type ESIndexConnectorType = ConnectorType< ConnectorTypeConfigType, diff --git a/x-pack/platform/plugins/shared/streams/server/lib/streams/data_streams/manage_data_streams.ts b/x-pack/platform/plugins/shared/streams/server/lib/streams/data_streams/manage_data_streams.ts index e10edef3a38d0..11a1e1ff5671e 100644 --- a/x-pack/platform/plugins/shared/streams/server/lib/streams/data_streams/manage_data_streams.ts +++ b/x-pack/platform/plugins/shared/streams/server/lib/streams/data_streams/manage_data_streams.ts @@ -112,7 +112,9 @@ export async function updateDataStreamsLifecycle({ () => esClient.indices.putDataLifecycle({ name: names, - data_retention: isDslLifecycle(lifecycle) ? lifecycle.dsl.data_retention : undefined, + lifecycle: { + data_retention: isDslLifecycle(lifecycle) ? lifecycle.dsl.data_retention : undefined, + }, }), { logger } ); diff --git a/x-pack/platform/plugins/shared/streams/server/lib/streams/stream_crud.ts b/x-pack/platform/plugins/shared/streams/server/lib/streams/stream_crud.ts index a8369cee7778a..ea019db2e0dba 100644 --- a/x-pack/platform/plugins/shared/streams/server/lib/streams/stream_crud.ts +++ b/x-pack/platform/plugins/shared/streams/server/lib/streams/stream_crud.ts @@ -86,9 +86,7 @@ export async function deleteUnmanagedStreamObjects({ ); await scopedClusterClient.asCurrentUser.ingest.putPipeline({ id: targetPipelineName, - body: { - processors: updatedProcessors, - }, + processors: updatedProcessors, }); } } diff --git a/x-pack/platform/plugins/shared/streams/server/routes/streams/crud/route.ts b/x-pack/platform/plugins/shared/streams/server/routes/streams/crud/route.ts index 4dd021b241f86..9c9e3324c1947 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/streams/crud/route.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/streams/crud/route.ts @@ -87,18 +87,16 @@ export const streamDetailRoute = createServerRoute({ // check doc count const docCountResponse = await scopedClusterClient.asCurrentUser.search({ index: indexPattern, - body: { - track_total_hits: true, - query: { - range: { - '@timestamp': { - gte: params.query.start, - lte: params.query.end, - }, + track_total_hits: true, + query: { + range: { + '@timestamp': { + gte: params.query.start, + lte: params.query.end, }, }, - size: 0, }, + size: 0, }); const count = (docCountResponse.hits.total as SearchTotalHits).value; diff --git a/x-pack/platform/plugins/shared/streams/server/routes/streams/management/route.ts b/x-pack/platform/plugins/shared/streams/server/routes/streams/management/route.ts index 7b6e9e0cdc1c5..18de62b68cf1a 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/streams/management/route.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/streams/management/route.ts @@ -144,14 +144,14 @@ export const sampleStreamRoute = createServerRoute({ ? Object.fromEntries( getFields(condition).map((field) => [ field.name, - { type: field.type === 'string' ? 'keyword' : 'double' }, + { type: field.type === 'string' ? ('keyword' as const) : ('double' as const) }, ]) ) : undefined, sort: [ { '@timestamp': { - order: 'desc', + order: 'desc' as const, }, }, ], diff --git a/x-pack/platform/plugins/shared/streams/server/routes/streams/processing/simulation_handler.ts b/x-pack/platform/plugins/shared/streams/server/routes/streams/processing/simulation_handler.ts index 5dbb3bd34d67f..12f3511aae136 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/streams/processing/simulation_handler.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/streams/processing/simulation_handler.ts @@ -9,14 +9,14 @@ import { errors as esErrors } from '@elastic/elasticsearch'; import { - IngestSimulateDocument, + IngestDocument, IngestProcessorContainer, IngestSimulateRequest, IngestPipelineConfig, ClusterComponentTemplateNode, ErrorCauseKeys, - IngestSimulatePipelineSimulation, - IngestSimulateSimulateDocumentResult, + IngestPipelineSimulation, + IngestSimulateDocumentResult, } from '@elastic/elasticsearch/lib/api/types'; import { IScopedClusterClient } from '@kbn/core/server'; import { flattenObjectNestedLast, calculateObjectDiff } from '@kbn/object-utils'; @@ -80,7 +80,7 @@ export interface ProcessorMetrics { // Narrow down the type to only successful processor results export type SuccessfulIngestSimulateDocumentResult = WithRequired< - IngestSimulateSimulateDocumentResult, + IngestSimulateDocumentResult, 'processor_results' >; @@ -146,7 +146,7 @@ export const simulateProcessing = async ({ const prepareSimulationDocs = ( documents: FlattenRecord[], streamName: string -): IngestSimulateDocument[] => { +): IngestDocument[] => { return documents.map((doc, id) => ({ _index: streamName, _id: id.toString(), @@ -224,7 +224,7 @@ const prepareIngestSimulationBody = ( // TODO: update type once Kibana updates to elasticsearch-js 8.17 const simulationBody: { - docs: IngestSimulateDocument[]; + docs: IngestDocument[]; pipeline_substitutions: Record; component_template_substitutions?: Record; } = { @@ -295,7 +295,7 @@ const executePipelineSimulation = async ( // TODO: update type to built-in once Kibana updates to elasticsearch-js 8.17 interface IngestSimulationResult { - docs: Array<{ doc: IngestSimulateDocument & { error?: ErrorCauseKeys } }>; + docs: Array<{ doc: IngestDocument & { error?: ErrorCauseKeys } }>; } const conditionallyExecuteIngestSimulation = async ( @@ -605,8 +605,8 @@ const computeMappingProperties = (detectedFields: NamedFieldDefinitionConfig[]) * Guard helpers */ const isSuccessfulProcessor = ( - processor: IngestSimulatePipelineSimulation -): processor is WithRequired => + processor: IngestPipelineSimulation +): processor is WithRequired => processor.status === 'success' && !!processor.tag; // TODO: update type once Kibana updates to elasticsearch-js 8.17 diff --git a/x-pack/platform/plugins/shared/streams/server/routes/streams/schema/route.ts b/x-pack/platform/plugins/shared/streams/server/routes/streams/schema/route.ts index 08cffd4296c4f..23172a1096ee5 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/streams/schema/route.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/streams/schema/route.ts @@ -39,7 +39,7 @@ export const unmappedFieldsRoute = createServerRoute({ sort: [ { '@timestamp': { - order: 'desc', + order: 'desc' as const, }, }, ], @@ -122,7 +122,7 @@ export const schemaFieldsSimulationRoute = createServerRoute({ } const propertiesForSample = Object.fromEntries( - params.body.field_definitions.map((field) => [field.name, { type: 'keyword' }]) + params.body.field_definitions.map((field) => [field.name, { type: 'keyword' as const }]) ); const documentSamplesSearchBody = { @@ -138,7 +138,7 @@ export const schemaFieldsSimulationRoute = createServerRoute({ sort: [ { '@timestamp': { - order: 'desc', + order: 'desc' as const, }, }, ], @@ -244,7 +244,7 @@ export const schemaFieldsSimulationRoute = createServerRoute({ sort: [ { '@timestamp': { - order: 'desc', + order: 'desc' as const, }, }, ], diff --git a/x-pack/platform/plugins/shared/task_manager/server/integration_tests/removed_types.test.ts b/x-pack/platform/plugins/shared/task_manager/server/integration_tests/removed_types.test.ts index 2698c96417a74..df4954bf08ac6 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/integration_tests/removed_types.test.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/integration_tests/removed_types.test.ts @@ -150,17 +150,15 @@ describe('unrecognized task types', () => { async function getTask(esClient: ElasticsearchClient) { const response = await esClient.search<{ task: ConcreteTaskInstance }>({ index: '.kibana_task_manager', - body: { - query: { - bool: { - filter: [ - { - term: { - 'task.taskType': 'sampleTaskRemovedType', - }, + query: { + bool: { + filter: [ + { + term: { + 'task.taskType': 'sampleTaskRemovedType', }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/platform/plugins/shared/task_manager/server/lib/bulk_operation_buffer.ts b/x-pack/platform/plugins/shared/task_manager/server/lib/bulk_operation_buffer.ts index 76a7fe338a7e5..e96945cde2730 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/lib/bulk_operation_buffer.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/lib/bulk_operation_buffer.ts @@ -7,7 +7,7 @@ import { Logger } from '@kbn/core/server'; import { map } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Subject, race, from } from 'rxjs'; import { bufferWhen, filter, bufferCount, flatMap, mapTo, first } from 'rxjs'; import { SavedObjectError } from '@kbn/core-saved-objects-common'; diff --git a/x-pack/platform/plugins/shared/task_manager/server/metrics/task_metrics_collector.ts b/x-pack/platform/plugins/shared/task_manager/server/metrics/task_metrics_collector.ts index 75b8a8beec5e8..4b064d013d2ef 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/metrics/task_metrics_collector.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/metrics/task_metrics_collector.ts @@ -10,7 +10,7 @@ import { AggregationsStringTermsBucket, AggregationsStringTermsBucketKeys, AggregationsTermsAggregateBase, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { Observable, Subject } from 'rxjs'; import { TaskStore } from '../task_store'; import { diff --git a/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.test.ts b/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.test.ts index 0326e07de6f48..7e8462bd582a0 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.test.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.test.ts @@ -21,7 +21,7 @@ import { times } from 'lodash'; import { taskStoreMock } from '../task_store.mock'; import { of, Subject } from 'rxjs'; import { sleep } from '../test_utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { TaskTypeDictionary } from '../task_type_dictionary'; type ResponseWithAggs = Omit, 'aggregations'> & { diff --git a/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.ts b/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.ts index 37f1291132547..e304c3f26b60c 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/monitoring/workload_statistics.ts @@ -10,7 +10,7 @@ import { mergeMap, map, filter, switchMap, catchError } from 'rxjs'; import { Logger } from '@kbn/core/server'; import { JsonObject } from '@kbn/utility-types'; import { keyBy, mapValues } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { AggregationResultOf } from '@kbn/es-types'; import { AggregatedStatProvider } from '../lib/runtime_statistics_aggregator'; import { parseIntervalAsSecond, asInterval, parseIntervalAsMillisecond } from '../lib/intervals'; diff --git a/x-pack/platform/plugins/shared/task_manager/server/plugin.ts b/x-pack/platform/plugins/shared/task_manager/server/plugin.ts index fda9f34d4665a..c27f5f0209a97 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/plugin.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/plugin.ts @@ -7,7 +7,7 @@ import { combineLatest, Observable, Subject, BehaviorSubject } from 'rxjs'; import { map, distinctUntilChanged } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { UsageCollectionSetup, UsageCollectionStart, diff --git a/x-pack/platform/plugins/shared/task_manager/server/queries/aggregate_task_overdue_percentiles_for_type.ts b/x-pack/platform/plugins/shared/task_manager/server/queries/aggregate_task_overdue_percentiles_for_type.ts index 67b28ce600e3a..dbeff5ea943a9 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/queries/aggregate_task_overdue_percentiles_for_type.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/queries/aggregate_task_overdue_percentiles_for_type.ts @@ -9,7 +9,7 @@ import type { AggregationsAggregationContainer, QueryDslQueryContainer, MappingRuntimeFields, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { IdleTaskWithExpiredRunAt, RunningOrClaimingTaskWithExpiredRetryAt, diff --git a/x-pack/platform/plugins/shared/task_manager/server/queries/mark_available_tasks_as_claimed.ts b/x-pack/platform/plugins/shared/task_manager/server/queries/mark_available_tasks_as_claimed.ts index b428cb0dd889d..09754b1734e08 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/queries/mark_available_tasks_as_claimed.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/queries/mark_available_tasks_as_claimed.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { TaskTypeDictionary } from '../task_type_dictionary'; import { TaskStatus, TaskPriority, ConcreteTaskInstance } from '../task'; import { diff --git a/x-pack/platform/plugins/shared/task_manager/server/queries/oldest_idle_action_task.ts b/x-pack/platform/plugins/shared/task_manager/server/queries/oldest_idle_action_task.ts index 69947cb08fc8d..b6884a26d4160 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/queries/oldest_idle_action_task.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/queries/oldest_idle_action_task.ts @@ -22,40 +22,38 @@ export const getOldestIdleActionTask = async ( { size: 1, index: taskManagerIndex, - body: { - sort: [{ 'task.runAt': { order: 'asc' } }], - query: { - bool: { - filter: { - bool: { - must: [ - { - terms: { - 'task.taskType': [ - 'actions:.email', - 'actions:.index', - 'actions:.pagerduty', - 'actions:.swimlane', - 'actions:.server-log', - 'actions:.slack', - 'actions:.webhook', - 'actions:.servicenow', - 'actions:.servicenow-sir', - 'actions:.jira', - 'actions:.resilient', - 'actions:.teams', - 'actions:.sentinelone', - ], - }, + sort: [{ 'task.runAt': { order: 'asc' } }], + query: { + bool: { + filter: { + bool: { + must: [ + { + terms: { + 'task.taskType': [ + 'actions:.email', + 'actions:.index', + 'actions:.pagerduty', + 'actions:.swimlane', + 'actions:.server-log', + 'actions:.slack', + 'actions:.webhook', + 'actions:.servicenow', + 'actions:.servicenow-sir', + 'actions:.jira', + 'actions:.resilient', + 'actions:.teams', + 'actions:.sentinelone', + ], }, - { - term: { type: 'task' }, - }, - { - term: { 'task.status': 'idle' }, - }, - ], - }, + }, + { + term: { type: 'task' }, + }, + { + term: { 'task.status': 'idle' }, + }, + ], }, }, }, diff --git a/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts b/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts index 140ae0659d329..6f09ec56a16e5 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface MustCondition { bool: Pick; diff --git a/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.test.ts b/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.test.ts index 1485216a67f33..1d60c926d212b 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.test.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.test.ts @@ -8,7 +8,7 @@ import { mockLogger } from '../test_utils'; import { coreMock, elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { SCHEDULE_INTERVAL, taskRunner } from './mark_removed_tasks_as_unrecognized'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; const createTaskDoc = (id: string = '1'): SearchHit => ({ _index: '.kibana_task_manager_9.0.0_001', diff --git a/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.ts b/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.ts index a0b518849d909..de146d95fdaac 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/removed_tasks/mark_removed_tasks_as_unrecognized.ts @@ -8,7 +8,7 @@ import { Logger } from '@kbn/logging'; import { CoreStart } from '@kbn/core-lifecycle-server'; import { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { TaskScheduling } from '../task_scheduling'; import { TaskTypeDictionary } from '../task_type_dictionary'; import { ConcreteTaskInstance, TaskManagerStartContract } from '..'; @@ -90,19 +90,17 @@ async function queryForRemovedTasks( ): Promise>> { const result = await esClient.search({ index: TASK_MANAGER_INDEX, - body: { - size: 100, - _source: false, - query: { - bool: { - must: [ - { - terms: { - 'task.taskType': REMOVED_TYPES, - }, + size: 100, + _source: false, + query: { + bool: { + must: [ + { + terms: { + 'task.taskType': REMOVED_TYPES, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.test.ts b/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.test.ts index 322060b4f9b61..13a352d18db43 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.test.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.test.ts @@ -15,7 +15,7 @@ import { usageCountersServiceMock } from '@kbn/usage-collection-plugin/server/us import { MonitoringStats } from '../monitoring'; import { configSchema, TaskManagerConfig } from '../config'; import { backgroundTaskUtilizationRoute } from './background_task_utilization'; -import { SecurityHasPrivilegesResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SecurityHasPrivilegesResponse } from '@elastic/elasticsearch/lib/api/types'; const mockUsageCountersSetup = usageCountersServiceMock.createSetupContract(); const mockUsageCounter = mockUsageCountersSetup.createUsageCounter('test'); @@ -118,15 +118,13 @@ describe('backgroundTaskUtilizationRoute', () => { await handler(context, req, res); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - application: [ - { - application: `kibana-foo`, - resources: ['*'], - privileges: [`api:8.0:taskManager`], - }, - ], - }, + application: [ + { + application: `kibana-foo`, + resources: ['*'], + privileges: [`api:8.0:taskManager`], + }, + ], }); expect(mockUsageCounter.incrementCounter).toHaveBeenCalledTimes(1); expect(mockUsageCounter.incrementCounter).toHaveBeenNthCalledWith(1, { @@ -158,15 +156,13 @@ describe('backgroundTaskUtilizationRoute', () => { await handler(context, req, res); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - application: [ - { - application: `kibana-foo`, - resources: ['*'], - privileges: [`api:8.0:taskManager`], - }, - ], - }, + application: [ + { + application: `kibana-foo`, + resources: ['*'], + privileges: [`api:8.0:taskManager`], + }, + ], }); expect(mockUsageCounter.incrementCounter).toHaveBeenCalledTimes(2); diff --git a/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.ts b/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.ts index 9f1de1eabbd8e..c0049ff74944c 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/routes/background_task_utilization.ts @@ -145,15 +145,13 @@ export function backgroundTaskUtilizationRoute( const hasPrivilegesResponse = await clusterClient .asScoped(req) .asCurrentUser.security.hasPrivileges({ - body: { - application: [ - { - application: `kibana-${kibanaIndexName}`, - resources: ['*'], - privileges: [`api:${kibanaVersion}:taskManager`], - }, - ], - }, + application: [ + { + application: `kibana-${kibanaIndexName}`, + resources: ['*'], + privileges: [`api:${kibanaVersion}:taskManager`], + }, + ], }); // Keep track of total access vs admin access diff --git a/x-pack/platform/plugins/shared/task_manager/server/routes/health.test.ts b/x-pack/platform/plugins/shared/task_manager/server/routes/health.test.ts index 112864019fe71..9d04e631e8e7e 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/routes/health.test.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/routes/health.test.ts @@ -121,15 +121,13 @@ describe('healthRoute', () => { await handler(context, req, res); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - application: [ - { - application: `kibana-foo`, - resources: ['*'], - privileges: [`api:8.0:taskManager`], - }, - ], - }, + application: [ + { + application: `kibana-foo`, + resources: ['*'], + privileges: [`api:8.0:taskManager`], + }, + ], }); expect(mockUsageCounter.incrementCounter).toHaveBeenCalledTimes(1); expect(mockUsageCounter.incrementCounter).toHaveBeenNthCalledWith(1, { @@ -164,15 +162,13 @@ describe('healthRoute', () => { await handler(context, req, res); expect(mockScopedClusterClient.asCurrentUser.security.hasPrivileges).toHaveBeenCalledWith({ - body: { - application: [ - { - application: `kibana-foo`, - resources: ['*'], - privileges: [`api:8.0:taskManager`], - }, - ], - }, + application: [ + { + application: `kibana-foo`, + resources: ['*'], + privileges: [`api:8.0:taskManager`], + }, + ], }); expect(mockUsageCounter.incrementCounter).toHaveBeenCalledTimes(2); diff --git a/x-pack/platform/plugins/shared/task_manager/server/routes/health.ts b/x-pack/platform/plugins/shared/task_manager/server/routes/health.ts index 10a5c838a585a..2053a31838202 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/routes/health.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/routes/health.ts @@ -171,15 +171,13 @@ export function healthRoute(params: HealthRouteParams): { const hasPrivilegesResponse = await clusterClient .asScoped(req) .asCurrentUser.security.hasPrivileges({ - body: { - application: [ - { - application: `kibana-${kibanaIndexName}`, - resources: ['*'], - privileges: [`api:${kibanaVersion}:taskManager`], - }, - ], - }, + application: [ + { + application: `kibana-${kibanaIndexName}`, + resources: ['*'], + privileges: [`api:${kibanaVersion}:taskManager`], + }, + ], }); // Keep track of total access vs admin access diff --git a/x-pack/platform/plugins/shared/task_manager/server/saved_objects/index.ts b/x-pack/platform/plugins/shared/task_manager/server/saved_objects/index.ts index dc1cd97677767..ad898b9daa3f1 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/saved_objects/index.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/saved_objects/index.ts @@ -6,7 +6,7 @@ */ import type { SavedObjectsServiceSetup } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { backgroundTaskNodeMapping, taskMappings } from './mappings'; import { getMigrations } from './migrations'; import { TaskManagerConfig } from '../config'; diff --git a/x-pack/platform/plugins/shared/task_manager/server/task_store.test.ts b/x-pack/platform/plugins/shared/task_manager/server/task_store.test.ts index c6a18b73ed31a..5c38e8b8801a4 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/task_store.test.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/task_store.test.ts @@ -7,7 +7,7 @@ import { schema } from '@kbn/config-schema'; import { Client } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import _ from 'lodash'; import { first } from 'rxjs'; @@ -321,10 +321,8 @@ describe('TaskStore', () => { const { args } = await testFetch(); expect(args).toMatchObject({ index: 'tasky', - body: { - sort: [{ 'task.runAt': 'asc' }], - query: { term: { type: 'task' } }, - }, + sort: [{ 'task.runAt': 'asc' }], + query: { term: { type: 'task' } }, }); }); @@ -336,11 +334,9 @@ describe('TaskStore', () => { }); expect(args).toMatchObject({ - body: { - query: { - bool: { - must: [{ term: { type: 'task' } }, { term: { 'task.taskType': 'bar' } }], - }, + query: { + bool: { + must: [{ term: { type: 'task' } }, { term: { 'task.taskType': 'bar' } }], }, }, }); @@ -357,10 +353,8 @@ describe('TaskStore', () => { const { args } = await testFetch({}, [], true); expect(args).toMatchObject({ index: 'tasky', - body: { - sort: [{ 'task.runAt': 'asc' }], - query: { term: { type: 'task' } }, - }, + sort: [{ 'task.runAt': 'asc' }], + query: { term: { type: 'task' } }, _source_excludes: ['task.state', 'task.params'], }); }); @@ -426,7 +420,7 @@ describe('TaskStore', () => { const { args } = await testMsearch([{}], []); expect(args).toMatchObject({ index: 'tasky', - body: [ + searches: [ {}, { sort: [{ 'task.runAt': 'asc' }], @@ -454,7 +448,7 @@ describe('TaskStore', () => { ); expect(args).toMatchObject({ - body: [ + searches: [ {}, { query: { @@ -553,20 +547,18 @@ describe('TaskStore', () => { }); expect(args).toMatchObject({ index: 'tasky', - body: { - size: 0, - query: { - bool: { - filter: { - bool: { - must: [{ term: { type: 'task' } }, { term: { 'task.enabled': true } }], - must_not: [{ term: { 'task.status': 'unrecognized' } }], - }, + size: 0, + query: { + bool: { + filter: { + bool: { + must: [{ term: { type: 'task' } }, { term: { 'task.enabled': true } }], + must_not: [{ term: { 'task.status': 'unrecognized' } }], }, }, }, - aggs: { testAgg: { terms: { field: 'task.taskType' } } }, }, + aggs: { testAgg: { terms: { field: 'task.taskType' } } }, }); }); @@ -579,27 +571,25 @@ describe('TaskStore', () => { }); expect(args).toMatchObject({ - body: { - size: 0, - query: { - bool: { - must: [ - { - bool: { - filter: { - bool: { - must: [{ term: { type: 'task' } }, { term: { 'task.enabled': true } }], - must_not: [{ term: { 'task.status': 'unrecognized' } }], - }, + size: 0, + query: { + bool: { + must: [ + { + bool: { + filter: { + bool: { + must: [{ term: { type: 'task' } }, { term: { 'task.enabled': true } }], + must_not: [{ term: { 'task.status': 'unrecognized' } }], }, }, }, - { term: { 'task.taskType': 'bar' } }, - ], - }, + }, + { term: { 'task.taskType': 'bar' } }, + ], }, - aggs: { testAgg: { terms: { field: 'task.taskType' } } }, }, + aggs: { testAgg: { terms: { field: 'task.taskType' } } }, }); }); @@ -610,21 +600,19 @@ describe('TaskStore', () => { }); expect(args).toMatchObject({ - body: { - size: 0, - query: { - bool: { - filter: { - bool: { - must: [{ term: { type: 'task' } }, { term: { 'task.enabled': true } }], - must_not: [{ term: { 'task.status': 'unrecognized' } }], - }, + size: 0, + query: { + bool: { + filter: { + bool: { + must: [{ term: { type: 'task' } }, { term: { 'task.enabled': true } }], + must_not: [{ term: { 'task.status': 'unrecognized' } }], }, }, }, - aggs: { testAgg: { terms: { field: 'task.taskType' } } }, - runtime_mappings: { testMapping: { type: 'long', script: { source: `` } } }, }, + aggs: { testAgg: { terms: { field: 'task.taskType' } } }, + runtime_mappings: { testMapping: { type: 'long', script: { source: `` } } }, }); }); diff --git a/x-pack/platform/plugins/shared/task_manager/server/task_store.ts b/x-pack/platform/plugins/shared/task_manager/server/task_store.ts index 6c48f3bd7552d..2bf28be6a5caa 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/task_store.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/task_store.ts @@ -14,7 +14,7 @@ import { Subject } from 'rxjs'; import { omit, defaults, get } from 'lodash'; import { SavedObjectError } from '@kbn/core-saved-objects-common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsBulkDeleteResponse, Logger } from '@kbn/core/server'; import { @@ -519,9 +519,7 @@ export class TaskStore { taskVersions = await this.esClientWithoutRetries.mget({ index: this.index, _source: false, - body: { - ids, - }, + ids, }); } catch (e) { this.errors$.next(e); @@ -579,12 +577,12 @@ export class TaskStore { const queries = opts.map(({ sort = [{ 'task.runAt': 'asc' }], ...opt }) => ensureQueryOnlyReturnsTaskObjects({ sort, ...opt }) ); - const body = queries.flatMap((query) => [{}, query]); + const searches = queries.flatMap((query) => [{}, query]); const result = await this.esClientWithoutRetries.msearch({ index: this.index, ignore_unavailable: true, - body, + searches, }); const { responses } = result; @@ -619,7 +617,8 @@ export class TaskStore { const result = await this.esClientWithoutRetries.search({ index: this.index, ignore_unavailable: true, - body: { ...opts, query }, + ...opts, + query, ...(limitResponse ? { _source_excludes: ['task.state', 'task.params'] } : {}), }); @@ -691,7 +690,7 @@ export class TaskStore { index: this.index, ignore_unavailable: true, track_total_hits: true, - body: ensureAggregationOnlyReturnsEnabledTaskObjects({ + ...ensureAggregationOnlyReturnsEnabledTaskObjects({ query, aggs, runtime_mappings, @@ -708,7 +707,9 @@ export class TaskStore { ): Promise { const { query } = ensureQueryOnlyReturnsTaskObjects(opts); try { - const // eslint-disable-next-line @typescript-eslint/naming-convention + const // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 types complain because the body should not be there. + // However, we can't use this API without the body because it fails to claim the tasks. + // eslint-disable-next-line @typescript-eslint/naming-convention { total, updated, version_conflicts } = await this.esClientWithoutRetries.updateByQuery( { index: this.index, diff --git a/x-pack/platform/plugins/shared/timelines/common/search_strategy/common/index.ts b/x-pack/platform/plugins/shared/timelines/common/search_strategy/common/index.ts index 63f43c936e77e..c7137e40b25a7 100644 --- a/x-pack/platform/plugins/shared/timelines/common/search_strategy/common/index.ts +++ b/x-pack/platform/plugins/shared/timelines/common/search_strategy/common/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export type Maybe = T | null; diff --git a/x-pack/platform/plugins/shared/timelines/common/search_strategy/index_fields/index.ts b/x-pack/platform/plugins/shared/timelines/common/search_strategy/index_fields/index.ts index 359eb48b6670a..7f0603bb2cdf8 100644 --- a/x-pack/platform/plugins/shared/timelines/common/search_strategy/index_fields/index.ts +++ b/x-pack/platform/plugins/shared/timelines/common/search_strategy/index_fields/index.ts @@ -6,7 +6,7 @@ */ import type { IEsSearchRequest, IEsSearchResponse } from '@kbn/search-types'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import type { FieldSpec } from '@kbn/data-plugin/common'; import type { Maybe } from '../common'; diff --git a/x-pack/platform/plugins/shared/timelines/public/mock/browser_fields.ts b/x-pack/platform/plugins/shared/timelines/public/mock/browser_fields.ts index 2dc8f369356f5..f6887a242a5ea 100644 --- a/x-pack/platform/plugins/shared/timelines/public/mock/browser_fields.ts +++ b/x-pack/platform/plugins/shared/timelines/public/mock/browser_fields.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; import type { BrowserFields } from '../../common/search_strategy/index_fields'; const DEFAULT_INDEX_PATTERN = [ diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.test.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.test.ts index e4b821924b721..b37827066903c 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.test.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.test.ts @@ -380,11 +380,13 @@ describe('Fields Provider', () => { expect(esClientSearchMock).toHaveBeenCalledWith({ index: indices[0], - body: { query: { match_all: {} }, size: 0 }, + query: { match_all: {} }, + size: 0, }); expect(esClientSearchMock).toHaveBeenCalledWith({ index: indices[1], - body: { query: { match_all: {} }, size: 0 }, + query: { match_all: {} }, + size: 0, }); expect(getFieldsForWildcardMock).not.toHaveBeenCalled(); @@ -413,11 +415,13 @@ describe('Fields Provider', () => { expect(esClientSearchMock).toHaveBeenCalledWith({ index: indices[0], - body: { query: { match_all: {} }, size: 0 }, + query: { match_all: {} }, + size: 0, }); expect(esClientSearchMock).toHaveBeenCalledWith({ index: indices[1], - body: { query: { match_all: {} }, size: 0 }, + query: { match_all: {} }, + size: 0, }); expect(getFieldsForWildcardMock).not.toHaveBeenCalled(); diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.ts index 6af36c4ad6f73..97ef61bb04589 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/index_fields/index.ts @@ -63,7 +63,8 @@ export const findExistingIndices = async ( if ([apmIndexPattern, apmDataStreamsPattern].includes(index)) { const searchResponse = await esClient.search({ index, - body: { query: { match_all: {} }, size: 0 }, + query: { match_all: {} }, + size: 0, }); return get(searchResponse, 'hits.total.value', 0) > 0; } diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.test.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.test.ts index 9a3a4a0261002..9e0a29c5a4e1f 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.test.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.test.ts @@ -39,53 +39,51 @@ describe('buildTimelineEventsAllQuery', () => { }); expect(query).toMatchInlineSnapshot(` Object { - "allow_no_indices": true, - "body": Object { - "_source": false, - "aggregations": Object { - "producers": Object { - "terms": Object { - "exclude": Array [ - "alerts", - ], - "field": "kibana.alert.rule.producer", - }, - }, - }, - "fields": Array [ - "signal.*", - "kibana.alert.*", - Object { - "field": "@timestamp", - "format": "strict_date_optional_time", - }, - ], - "from": 0, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "match_all": Object {}, - }, + "_source": false, + "aggregations": Object { + "producers": Object { + "terms": Object { + "exclude": Array [ + "alerts", ], + "field": "kibana.alert.rule.producer", }, }, - "runtime_mappings": Object {}, - "size": 100, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", - "unmapped_type": "date", - }, - }, - ], - "track_total_hits": true, }, + "allow_no_indices": true, + "fields": Array [ + "signal.*", + "kibana.alert.*", + Object { + "field": "@timestamp", + "format": "strict_date_optional_time", + }, + ], + "from": 0, "ignore_unavailable": true, "index": Array [ ".siem-signals-default", ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "match_all": Object {}, + }, + ], + }, + }, + "runtime_mappings": Object {}, + "size": 100, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + "unmapped_type": "date", + }, + }, + ], + "track_total_hits": true, } `); }); diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts index 2695ed06132bb..54734d3ceada8 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts @@ -66,33 +66,31 @@ export const buildTimelineEventsAllQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: { - producers: { - terms: { field: ALERT_RULE_PRODUCER, exclude: ['alerts'] }, - }, + aggregations: { + producers: { + terms: { field: ALERT_RULE_PRODUCER, exclude: ['alerts'] }, }, - query: { - bool: { - filter, - }, + }, + query: { + bool: { + filter, }, - runtime_mappings: runtimeMappings, - from: activePage * querySize, - size: querySize, - track_total_hits: true, - sort: getSortField(sort), - fields: [ - 'signal.*', - 'kibana.alert.*', - ...fields, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - _source: false, }, + runtime_mappings: runtimeMappings, + from: activePage * querySize, + size: querySize, + track_total_hits: true, + sort: getSortField(sort), + fields: [ + 'signal.*', + 'kibana.alert.*', + ...fields, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + _source: false, }; return dslQuery; diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.test.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.test.ts index d2383c979d29a..73615e9004d7c 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.test.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.test.ts @@ -20,42 +20,40 @@ describe('buildTimelineDetailsQuery', () => { expect(query).toMatchInlineSnapshot(` Object { + "_source": true, "allow_no_indices": true, - "body": Object { - "_source": true, - "fields": Array [ - Object { - "field": "*", - "include_unmapped": true, - }, - Object { - "field": "@timestamp", - "format": "strict_date_optional_time", - }, - Object { - "field": "code_signature.timestamp", - "format": "strict_date_optional_time", - }, - Object { - "field": "dll.code_signature.timestamp", - "format": "strict_date_optional_time", - }, - ], - "query": Object { - "terms": Object { - "_id": Array [ - "f0a936d50b5b3a5a193d415459c14587fe633f7e519df7b5dc151d56142680e3", - ], - }, + "fields": Array [ + Object { + "field": "*", + "include_unmapped": true, }, - "runtime_mappings": Object {}, - "stored_fields": Array [ - "*", - ], - }, + Object { + "field": "@timestamp", + "format": "strict_date_optional_time", + }, + Object { + "field": "code_signature.timestamp", + "format": "strict_date_optional_time", + }, + Object { + "field": "dll.code_signature.timestamp", + "format": "strict_date_optional_time", + }, + ], "ignore_unavailable": true, "index": ".siem-signals-default", + "query": Object { + "terms": Object { + "_id": Array [ + "f0a936d50b5b3a5a193d415459c14587fe633f7e519df7b5dc151d56142680e3", + ], + }, + }, + "runtime_mappings": Object {}, "size": 1, + "stored_fields": Array [ + "*", + ], } `); }); diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts index defd6444162f8..f7a8f7f5e05d4 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts @@ -41,28 +41,26 @@ export const buildTimelineDetailsQuery = ({ allow_no_indices: true, index: indexName, ignore_unavailable: true, - body: { - query, - fields: [ - { field: '*', include_unmapped: true }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - { - field: 'code_signature.timestamp', - format: 'strict_date_optional_time', - }, - { - field: 'dll.code_signature.timestamp', - format: 'strict_date_optional_time', - }, - ], - // Remove and instead pass index_pattern.id once issue resolved: https://github.com/elastic/kibana/issues/111762 - runtime_mappings: runtimeMappings, - stored_fields: ['*'], - _source: true, - }, + query, + fields: [ + { field: '*', include_unmapped: true }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + { + field: 'code_signature.timestamp', + format: 'strict_date_optional_time', + }, + { + field: 'dll.code_signature.timestamp', + format: 'strict_date_optional_time', + }, + ], + // Remove and instead pass index_pattern.id once issue resolved: https://github.com/elastic/kibana/issues/111762 + runtime_mappings: runtimeMappings, + stored_fields: ['*'], + _source: true, size: 1, }; }; diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/kpi/query.kpi.dsl.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/kpi/query.kpi.dsl.ts index fd98122a12eea..6025fa0ffacea 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/kpi/query.kpi.dsl.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/kpi/query.kpi.dsl.ts @@ -44,41 +44,39 @@ export const buildTimelineKpiQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggs: { - userCount: { - cardinality: { - field: 'user.id', - }, + aggs: { + userCount: { + cardinality: { + field: 'user.id', }, - destinationIpCount: { - cardinality: { - field: 'destination.ip', - }, - }, - hostCount: { - cardinality: { - field: 'host.id', - }, + }, + destinationIpCount: { + cardinality: { + field: 'destination.ip', }, - processCount: { - cardinality: { - field: 'process.entity_id', - }, + }, + hostCount: { + cardinality: { + field: 'host.id', }, - sourceIpCount: { - cardinality: { - field: 'source.ip', - }, + }, + processCount: { + cardinality: { + field: 'process.entity_id', }, }, - query: { - bool: { - filter, + sourceIpCount: { + cardinality: { + field: 'source.ip', }, }, - track_total_hits: true, }, + query: { + bool: { + filter, + }, + }, + track_total_hits: true, }; return dslQuery; diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.test.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.test.ts index 0a73089aaf321..987d3f89cd966 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.test.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.test.ts @@ -20,47 +20,45 @@ describe('buildLastEventTimeQuery', () => { }); expect(query).toMatchInlineSnapshot(` Object { + "_source": false, "allow_no_indices": true, - "body": Object { - "_source": false, - "fields": Array [ - Object { - "field": "@timestamp", - "format": "strict_date_optional_time", - }, - ], - "query": Object { - "bool": Object { - "filter": Object { - "bool": Object { - "should": Array [ - Object { - "term": Object { - "source.ip": "12345567", - }, + "fields": Array [ + Object { + "field": "@timestamp", + "format": "strict_date_optional_time", + }, + ], + "ignore_unavailable": true, + "index": Array [ + ".siem-signals-default", + ], + "query": Object { + "bool": Object { + "filter": Object { + "bool": Object { + "should": Array [ + Object { + "term": Object { + "source.ip": "12345567", }, - Object { - "term": Object { - "destination.ip": "12345567", - }, + }, + Object { + "term": Object { + "destination.ip": "12345567", }, - ], - }, + }, + ], }, }, }, - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, - }, - ], }, - "ignore_unavailable": true, - "index": Array [ - ".siem-signals-default", + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, ], "track_total_hits": false, } diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.ts index b707eb07fbf34..0e0c86dbbb9ba 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/events/last_event_time/query.events_last_event_time.dsl.ts @@ -41,24 +41,22 @@ export const buildLastEventTimeQuery = ({ index: indicesToQuery.network, ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter: { bool: { should: getIpDetailsFilter(details.ip) } } } }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - sort: [ - { - '@timestamp': { - order: 'desc', - }, + query: { bool: { filter: { bool: { should: getIpDetailsFilter(details.ip) } } } }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, + sort: [ + { + '@timestamp': { + order: 'desc', }, - ], - }, + }, + ], }; } throw new Error('buildLastEventTimeQuery - no IP argument provided'); @@ -69,24 +67,22 @@ export const buildLastEventTimeQuery = ({ index: indicesToQuery.hosts, ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter: getHostDetailsFilter(details.hostName) } }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - sort: [ - { - '@timestamp': { - order: 'desc', - }, + query: { bool: { filter: getHostDetailsFilter(details.hostName) } }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, + sort: [ + { + '@timestamp': { + order: 'desc', }, - ], - }, + }, + ], }; } throw new Error('buildLastEventTimeQuery - no hostName argument provided'); @@ -97,37 +93,7 @@ export const buildLastEventTimeQuery = ({ index: indicesToQuery.hosts, ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter: getUserDetailsFilter(details.userName) } }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - sort: [ - { - '@timestamp': { - order: 'desc', - }, - }, - ], - }, - }; - } - throw new Error('buildLastEventTimeQuery - no userName argument provided'); - case LastEventIndexKey.hosts: - case LastEventIndexKey.network: - case LastEventIndexKey.users: - return { - allow_no_indices: true, - index: indicesToQuery[indexKey], - ignore_unavailable: true, - track_total_hits: false, - body: { - query: { match_all: {} }, + query: { bool: { filter: getUserDetailsFilter(details.userName) } }, _source: false, fields: [ { @@ -143,7 +109,33 @@ export const buildLastEventTimeQuery = ({ }, }, ], - }, + }; + } + throw new Error('buildLastEventTimeQuery - no userName argument provided'); + case LastEventIndexKey.hosts: + case LastEventIndexKey.network: + case LastEventIndexKey.users: + return { + allow_no_indices: true, + index: indicesToQuery[indexKey], + ignore_unavailable: true, + track_total_hits: false, + query: { match_all: {} }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, + sort: [ + { + '@timestamp': { + order: 'desc', + }, + }, + ], }; default: return assertUnreachable(eventIndexKey); diff --git a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/helpers/is_agg_cardinality_aggregate.ts b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/helpers/is_agg_cardinality_aggregate.ts index 387d9c9a8ba26..3ad384f58dde2 100644 --- a/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/helpers/is_agg_cardinality_aggregate.ts +++ b/x-pack/platform/plugins/shared/timelines/server/search_strategy/timeline/factory/helpers/is_agg_cardinality_aggregate.ts @@ -7,7 +7,7 @@ import { AggregationsAggregate, AggregationsCardinalityAggregate, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; // type guard for checking if the Aggregation for a given field is a Cardinality // Agregate with valid value diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/build_agg.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/build_agg.ts index 0a5bc5cc97fe2..22d95c86a1ff1 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/build_agg.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/build_agg.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import { DateRangeInfo, getDateRangeInfo } from './date_range_info'; export interface BuildAggregationOpts { diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/parse_aggregation_results.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/parse_aggregation_results.ts index 95f10e9c60bd4..c4be68109e607 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/parse_aggregation_results.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/common/data/lib/parse_aggregation_results.ts @@ -10,7 +10,7 @@ import { SearchHit, SearchHitsMetadata, AggregationsSingleMetricAggregateBase, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { Group } from '@kbn/alerting-rule-utils'; export const UngroupedGroupId = 'all documents'; diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts index c8053ca571477..63815be4cf843 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts @@ -6,7 +6,7 @@ */ import { useEffect, useState, useCallback, useRef } from 'react'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { AsApiContract } from '@kbn/actions-plugin/common'; import { HttpSetup } from '@kbn/core/public'; import { BASE_RAC_ALERTS_API_PATH } from '@kbn/rule-registry-plugin/common/constants'; diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/action_connector_api/load_execution_log_aggregations.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/action_connector_api/load_execution_log_aggregations.ts index 76a96fe300359..7d22ae8080cef 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/action_connector_api/load_execution_log_aggregations.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/action_connector_api/load_execution_log_aggregations.ts @@ -8,7 +8,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { HttpSetup } from '@kbn/core/public'; -import type { SortOrder } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SortOrder } from '@elastic/elasticsearch/lib/api/types'; import { IExecutionLog, ExecutionLogSortFields, diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts index 7bfef44335a4c..3cd0f0cd56a35 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_action_error_log.ts @@ -6,7 +6,7 @@ */ import { HttpSetup } from '@kbn/core/public'; -import type { SortOrder } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SortOrder } from '@elastic/elasticsearch/lib/api/types'; import { IExecutionErrorsResult, ActionErrorLogSortFields } from '@kbn/alerting-plugin/common'; import { INTERNAL_BASE_ALERTING_API_PATH } from '../../constants'; import { getFilter } from './get_filter'; diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts index 334b4aea135a2..ffd01a0adcecc 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/lib/rule_api/load_execution_log_aggregations.ts @@ -8,7 +8,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { HttpSetup } from '@kbn/core/public'; -import type { SortOrder } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SortOrder } from '@elastic/elasticsearch/lib/api/types'; import { IExecutionLog, ExecutionLogSortFields, diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts index 88b40289cb6e0..332481b22e48e 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts @@ -6,7 +6,7 @@ */ import type { BrushEndListener, PartialTheme, SettingsProps, Theme } from '@elastic/charts'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { IUiSettingsClient } from '@kbn/core-ui-settings-browser'; import { AlertStatus } from '@kbn/rule-data-utils'; import { ChartsPluginStart } from '@kbn/charts-plugin/public'; diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.test.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.test.ts index efc802dc73d3c..4c1e22a87a398 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.test.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { Logger } from '@kbn/core/server'; import { TimeSeriesQuery, timeSeriesQuery, getResultFromEs } from './time_series_query'; @@ -61,7 +61,7 @@ describe('timeSeriesQuery', () => { query: { ...params.query, filterKuery: 'event.provider: alerting' }, }); // @ts-ignore - expect(esClient.search.mock.calls[0]![0].body.query.bool.filter[1]).toEqual({ + expect(esClient.search.mock.calls[0]![0].query.bool.filter[1]).toEqual({ bool: { minimum_should_match: 1, should: [ @@ -80,42 +80,40 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, - }, - }, - query: { - bool: { - filter: [ + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, - }, + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', + }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', }, ], }, }, - size: 0, }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', + }, + }, + }, + ], + }, + }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -134,42 +132,40 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, - }, - }, - query: { - bool: { - filter: [ + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, - }, + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', + }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', }, ], }, }, - size: 0, }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', + }, + }, + }, + ], + }, + }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -189,50 +185,48 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - terms: { - field: 'the-term', - size: 10, - }, - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, + aggs: { + groupAgg: { + terms: { + field: 'the-term', + size: 10, + }, + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', + }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, }, }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -256,63 +250,61 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - terms: { - field: 'the-term', - size: 10, - }, - aggs: { - conditionSelector: { - bucket_selector: { - buckets_path: { - compareValue: '_count', - }, - script: `params.compareValue > 1`, + aggs: { + groupAgg: { + terms: { + field: 'the-term', + size: 10, + }, + aggs: { + conditionSelector: { + bucket_selector: { + buckets_path: { + compareValue: '_count', }, + script: `params.compareValue > 1`, }, - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, + }, + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', + }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, }, }, - groupAggCount: { - stats_bucket: { - buckets_path: 'groupAgg._count', - }, + }, + groupAggCount: { + stats_bucket: { + buckets_path: 'groupAgg._count', }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -332,54 +324,52 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, - aggs: { - metricAgg: { - avg: { - field: 'avg-field', - }, + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', }, - }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, - sortValueAgg: { - avg: { - field: 'avg-field', + aggs: { + metricAgg: { + avg: { + field: 'avg-field', + }, }, }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + sortValueAgg: { + avg: { + field: 'avg-field', + }, + }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -403,54 +393,52 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, - aggs: { - metricAgg: { - avg: { - field: 'avg-field', - }, + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', }, - }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, - sortValueAgg: { - avg: { - field: 'avg-field', + aggs: { + metricAgg: { + avg: { + field: 'avg-field', + }, }, }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + sortValueAgg: { + avg: { + field: 'avg-field', + }, + }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -472,65 +460,63 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - terms: { - field: 'the-field', - order: { - sortValueAgg: 'desc', - }, - size: 20, + aggs: { + groupAgg: { + terms: { + field: 'the-field', + order: { + sortValueAgg: 'desc', }, - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, - aggs: { - metricAgg: { - avg: { - field: 'avg-field', - }, + size: 20, + }, + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', }, - }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, - sortValueAgg: { - avg: { - field: 'avg-field', + aggs: { + metricAgg: { + avg: { + field: 'avg-field', + }, }, }, }, + sortValueAgg: { + avg: { + field: 'avg-field', + }, + }, }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -556,78 +542,76 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - terms: { - field: 'the-field', - order: { - sortValueAgg: 'desc', - }, - size: 20, + aggs: { + groupAgg: { + terms: { + field: 'the-field', + order: { + sortValueAgg: 'desc', }, - aggs: { - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, - aggs: { - metricAgg: { - avg: { - field: 'avg-field', - }, + size: 20, + }, + aggs: { + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', }, - }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, - conditionSelector: { - bucket_selector: { - buckets_path: { - compareValue: 'sortValueAgg', + aggs: { + metricAgg: { + avg: { + field: 'avg-field', }, - script: 'params.compareValue > 1', }, }, - sortValueAgg: { - avg: { - field: 'avg-field', + }, + conditionSelector: { + bucket_selector: { + buckets_path: { + compareValue: 'sortValueAgg', }, + script: 'params.compareValue > 1', }, }, - }, - groupAggCount: { - stats_bucket: { - buckets_path: 'groupAgg._count', + sortValueAgg: { + avg: { + field: 'avg-field', + }, }, }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + groupAggCount: { + stats_bucket: { + buckets_path: 'groupAgg._count', + }, + }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -651,63 +635,61 @@ describe('timeSeriesQuery', () => { expect(esClient.search).toHaveBeenCalledWith( { allow_no_indices: true, - body: { - aggs: { - groupAgg: { - terms: { - field: 'the-term', - size: 6, - }, - aggs: { - conditionSelector: { - bucket_selector: { - buckets_path: { - compareValue: '_count', - }, - script: `params.compareValue > 1`, + aggs: { + groupAgg: { + terms: { + field: 'the-term', + size: 6, + }, + aggs: { + conditionSelector: { + bucket_selector: { + buckets_path: { + compareValue: '_count', }, + script: `params.compareValue > 1`, }, - dateAgg: { - date_range: { - field: 'time-field', - format: 'strict_date_time', - ranges: [ - { - from: '2021-04-22T15:14:31.000Z', - to: '2021-04-22T15:19:31.000Z', - }, - { - from: '2021-04-22T15:15:31.000Z', - to: '2021-04-22T15:20:31.000Z', - }, - ], - }, + }, + dateAgg: { + date_range: { + field: 'time-field', + format: 'strict_date_time', + ranges: [ + { + from: '2021-04-22T15:14:31.000Z', + to: '2021-04-22T15:19:31.000Z', + }, + { + from: '2021-04-22T15:15:31.000Z', + to: '2021-04-22T15:20:31.000Z', + }, + ], }, }, }, - groupAggCount: { - stats_bucket: { - buckets_path: 'groupAgg._count', - }, + }, + groupAggCount: { + stats_bucket: { + buckets_path: 'groupAgg._count', }, }, - query: { - bool: { - filter: [ - { - range: { - 'time-field': { - format: 'strict_date_time', - gte: '2021-04-22T15:14:31.000Z', - lt: '2021-04-22T15:20:31.000Z', - }, + }, + query: { + bool: { + filter: [ + { + range: { + 'time-field': { + format: 'strict_date_time', + gte: '2021-04-22T15:14:31.000Z', + lt: '2021-04-22T15:20:31.000Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: 'index-name', }, @@ -715,7 +697,7 @@ describe('timeSeriesQuery', () => { ); }); - it('uses the passed in date parms when useCalculatedDateRange = false param is passed', async () => { + it('uses the passed in date params when useCalculatedDateRange = false param is passed', async () => { await timeSeriesQuery({ ...params, useCalculatedDateRange: false, @@ -726,7 +708,7 @@ describe('timeSeriesQuery', () => { }, }); // @ts-ignore - expect(esClient.search.mock.calls[0]![0].body.query.bool.filter[0]).toEqual({ + expect(esClient.search.mock.calls[0]![0].query.bool.filter[0]).toEqual({ range: { 'time-field': { format: 'strict_date_time', diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.ts index 2e73bb60d2382..25b390ad9be71 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/lib/time_series_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Logger } from '@kbn/core/server'; import type { ElasticsearchClient } from '@kbn/core/server'; import { getEsErrorMessage } from '@kbn/alerting-plugin/server'; @@ -64,43 +64,40 @@ export async function timeSeriesQuery( // core query // Constructing a typesafe ES query in JS is problematic, use any escapehatch for now - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const esQuery: any = { + const esQuery = { index, - body: { - size: 0, - query: { - bool: { - filter: [ - { - range: { - [timeField]: { - gte: useCalculatedDateRange ? dateRangeInfo.dateStart : dateStart, - lt: useCalculatedDateRange ? dateRangeInfo.dateEnd : dateEnd, - format: 'strict_date_time', - }, + size: 0, + query: { + bool: { + filter: [ + { + range: { + [timeField]: { + gte: useCalculatedDateRange ? dateRangeInfo.dateStart : dateStart, + lt: useCalculatedDateRange ? dateRangeInfo.dateEnd : dateEnd, + format: 'strict_date_time', }, }, - ...(!!filterKuery ? [toElasticsearchQuery(fromKueryExpression(filterKuery))] : []), - ], - }, + }, + ...(!!filterKuery ? [toElasticsearchQuery(fromKueryExpression(filterKuery))] : []), + ], }, - aggs: buildAggregation({ - timeSeries: { - timeField, - timeWindowSize, - timeWindowUnit, - dateStart, - dateEnd, - interval, - }, - aggType, - aggField, - termField, - termSize, - condition: conditionParams, - }), }, + aggs: buildAggregation({ + timeSeries: { + timeField, + timeWindowSize, + timeWindowUnit, + dateStart, + dateEnd, + interval, + }, + aggType, + aggField, + termField, + termSize, + condition: conditionParams, + }), ignore_unavailable: true, allow_no_indices: true, }; diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/routes/indices.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/routes/indices.ts index 282092f2a25aa..3751e53b4cff1 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/routes/indices.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/server/data/routes/indices.ts @@ -106,14 +106,12 @@ async function getIndicesFromPattern( const params = { index: pattern, ignore_unavailable: true, - body: { - size: 0, // no hits - aggs: { - indices: { - terms: { - field: '_index', - size: MAX_INDICES, - }, + size: 0, // no hits + aggs: { + indices: { + terms: { + field: '_index', + size: MAX_INDICES, }, }, }, diff --git a/x-pack/solutions/observability/packages/alert-details/src/hooks/use_alerts_history.ts b/x-pack/solutions/observability/packages/alert-details/src/hooks/use_alerts_history.ts index a84fa74394cf4..bd525103449b0 100644 --- a/x-pack/solutions/observability/packages/alert-details/src/hooks/use_alerts_history.ts +++ b/x-pack/solutions/observability/packages/alert-details/src/hooks/use_alerts_history.ts @@ -6,7 +6,7 @@ */ import { type HttpSetup } from '@kbn/core/public'; -import { AggregationsDateHistogramBucketKeys } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsDateHistogramBucketKeys } from '@elastic/elasticsearch/lib/api/types'; import { ALERT_DURATION, ALERT_INSTANCE_ID, diff --git a/x-pack/solutions/observability/packages/utils-server/entities/get_log_patterns.ts b/x-pack/solutions/observability/packages/utils-server/entities/get_log_patterns.ts index d179d8d2bfab7..712a5aa6ef138 100644 --- a/x-pack/solutions/observability/packages/utils-server/entities/get_log_patterns.ts +++ b/x-pack/solutions/observability/packages/utils-server/entities/get_log_patterns.ts @@ -6,6 +6,7 @@ */ import { + AggregationsAggregationContainer, AggregationsCategorizeTextAggregation, AggregationsDateHistogramAggregation, AggregationsMaxAggregation, @@ -32,7 +33,7 @@ interface FieldPatternResultBase { firstOccurrence: string; lastOccurrence: string; highlight: Record; - metadata: Record; + metadata: Record; } interface FieldPatternResultChanges { @@ -63,8 +64,8 @@ interface CategorizeTextOptions { start: number; end: number; } -// eslint-disable-next-line @typescript-eslint/consistent-type-definitions -type CategorizeTextSubAggregations = { + +type CategorizeTextSubAggregations = Record & { sample: { top_hits: AggregationsTopHitsAggregation }; minTimestamp: { min: AggregationsMinAggregation }; maxTimestamp: { max: AggregationsMaxAggregation }; @@ -213,28 +214,35 @@ export async function runCategorizeTextAggregation({ count: bucket.doc_count, pattern: bucket.key, regex: bucket.regex, - sample: bucket.sample.hits.hits[0].fields![fieldName][0] as string, + sample: bucket.sample.hits.hits[0].fields![fieldName]![0] as string, highlight: bucket.sample.hits.hits[0].highlight ?? {}, metadata: bucket.sample.hits.hits[0].fields!, firstOccurrence: new Date(bucket.minTimestamp.value!).toISOString(), lastOccurrence: new Date(bucket.maxTimestamp.value!).toISOString(), ...('timeseries' in bucket ? { + // @ts-expect-error timeseries result types can't be inferred timeseries: bucket.timeseries.buckets.map((dateBucket) => ({ x: dateBucket.key, y: dateBucket.doc_count, })), + // @ts-expect-error changes result types can't be inferred change: Object.entries(bucket.changes.type).map( ([changePointType, change]): FieldPatternResultChanges['change'] => { return { type: changePointType as ChangePointType, significance: + // @ts-expect-error changes result types can't be inferred change.p_value !== undefined ? pValueToLabel(change.p_value) : null, + // @ts-expect-error changes result types can't be inferred change_point: change.change_point, + // @ts-expect-error changes result types can't be inferred p_value: change.p_value, timestamp: + // @ts-expect-error changes result types can't be inferred change.change_point !== undefined - ? bucket.timeseries.buckets[change.change_point].key_as_string + ? // @ts-expect-error changes and timeseries result types can't be inferred + bucket.timeseries.buckets[change.change_point].key_as_string : undefined, }; } diff --git a/x-pack/solutions/observability/plugins/apm/common/correlations/field_stats_types.ts b/x-pack/solutions/observability/plugins/apm/common/correlations/field_stats_types.ts index 51a601dd39c18..b66aedbe77156 100644 --- a/x-pack/solutions/observability/plugins/apm/common/correlations/field_stats_types.ts +++ b/x-pack/solutions/observability/plugins/apm/common/correlations/field_stats_types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface Field { fieldName: string; diff --git a/x-pack/solutions/observability/plugins/apm/common/correlations/types.ts b/x-pack/solutions/observability/plugins/apm/common/correlations/types.ts index 766afb38e4176..36a0badf7f06c 100644 --- a/x-pack/solutions/observability/plugins/apm/common/correlations/types.ts +++ b/x-pack/solutions/observability/plugins/apm/common/correlations/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { Environment } from '../environment_rt'; export interface FieldValuePair { diff --git a/x-pack/solutions/observability/plugins/apm/common/utils/environment_query.ts b/x-pack/solutions/observability/plugins/apm/common/utils/environment_query.ts index b31f1730d08b1..3fd5fe7653437 100644 --- a/x-pack/solutions/observability/plugins/apm/common/utils/environment_query.ts +++ b/x-pack/solutions/observability/plugins/apm/common/utils/environment_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SERVICE_ENVIRONMENT, SERVICE_NODE_NAME } from '../es_fields/apm'; import { ENVIRONMENT_ALL, ENVIRONMENT_NOT_DEFINED } from '../environment_filter_values'; import { SERVICE_NODE_NAME_MISSING } from '../service_nodes'; diff --git a/x-pack/solutions/observability/plugins/apm/public/components/app/correlations/context_popover/field_stats_popover.tsx b/x-pack/solutions/observability/plugins/apm/public/components/app/correlations/context_popover/field_stats_popover.tsx index 8983e2f2836c1..69171da6e6651 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/app/correlations/context_popover/field_stats_popover.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/app/correlations/context_popover/field_stats_popover.tsx @@ -26,7 +26,7 @@ import { } from '@kbn/unified-field-list/src/components/field_stats'; import { EuiHorizontalRule, EuiText, EuiSpacer, EuiLoadingSpinner } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import numeral from '@elastic/numeral'; import { css } from '@emotion/react'; diff --git a/x-pack/solutions/observability/plugins/apm/public/components/shared/kuery_bar/index.tsx b/x-pack/solutions/observability/plugins/apm/public/components/shared/kuery_bar/index.tsx index 3d800d6bb4167..87bebfb3e9a44 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/shared/kuery_bar/index.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/shared/kuery_bar/index.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import { uniqueId } from 'lodash'; import React, { useState } from 'react'; diff --git a/x-pack/solutions/observability/plugins/apm/public/components/shared/search_bar/search_bar.tsx b/x-pack/solutions/observability/plugins/apm/public/components/shared/search_bar/search_bar.tsx index dd82f303feaca..795174f7fe3ab 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/shared/search_bar/search_bar.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/shared/search_bar/search_bar.tsx @@ -7,7 +7,7 @@ import type { EuiFlexGroupProps } from '@elastic/eui'; import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; import React from 'react'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { useBreakpoints } from '../../../hooks/use_breakpoints'; import { TimeComparison } from '../time_comparison'; import { TransactionTypeSelect } from '../transaction_type_select'; diff --git a/x-pack/solutions/observability/plugins/apm/public/components/shared/unified_search_bar/index.tsx b/x-pack/solutions/observability/plugins/apm/public/components/shared/unified_search_bar/index.tsx index ac2b67b8b9c94..8468746116fdb 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/shared/unified_search_bar/index.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/shared/unified_search_bar/index.tsx @@ -18,7 +18,7 @@ import { useKibana } from '@kbn/kibana-react-plugin/public'; import qs from 'query-string'; import type { DataView } from '@kbn/data-plugin/common'; import { UI_SETTINGS } from '@kbn/data-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { OnRefreshChangeProps } from '@elastic/eui/src/components/date_picker/types'; import type { UIProcessorEvent } from '../../../../common/processor_event'; import type { TimePickerTimeDefaults } from '../date_picker/typings'; diff --git a/x-pack/solutions/observability/plugins/apm/scripts/create_functional_tests_archive/index.ts b/x-pack/solutions/observability/plugins/apm/scripts/create_functional_tests_archive/index.ts index 5846b3b1bc6cb..273bff9536b98 100644 --- a/x-pack/solutions/observability/plugins/apm/scripts/create_functional_tests_archive/index.ts +++ b/x-pack/solutions/observability/plugins/apm/scripts/create_functional_tests_archive/index.ts @@ -10,7 +10,7 @@ import { execSync } from 'child_process'; import moment from 'moment'; import path from 'path'; import fs from 'fs'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { REPO_ROOT } from '@kbn/repo-info'; import { getEsClient } from '../shared/get_es_client'; import { parseIndexUrl } from '../shared/parse_index_url'; diff --git a/x-pack/solutions/observability/plugins/apm/scripts/diagnostics_bundle/diagnostics_bundle.ts b/x-pack/solutions/observability/plugins/apm/scripts/diagnostics_bundle/diagnostics_bundle.ts index 10d55aa2000e1..1c24c67c48cd9 100644 --- a/x-pack/solutions/observability/plugins/apm/scripts/diagnostics_bundle/diagnostics_bundle.ts +++ b/x-pack/solutions/observability/plugins/apm/scripts/diagnostics_bundle/diagnostics_bundle.ts @@ -7,7 +7,7 @@ /* eslint-disable no-console */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import fs from 'fs/promises'; import type { AxiosRequestConfig } from 'axios'; import axios from 'axios'; @@ -47,6 +47,8 @@ export async function initDiagnosticsBundle({ ...(cloudId ? { cloud: { id: cloudId } } : {}), auth, headers: { ...apiKeyHeader }, + Connection: HttpConnection, + requestTimeout: 30_000, }); const kibanaClientOpts = { diff --git a/x-pack/solutions/observability/plugins/apm/scripts/shared/get_es_client.ts b/x-pack/solutions/observability/plugins/apm/scripts/shared/get_es_client.ts index 895b8cbacee86..af72e9674450b 100644 --- a/x-pack/solutions/observability/plugins/apm/scripts/shared/get_es_client.ts +++ b/x-pack/solutions/observability/plugins/apm/scripts/shared/get_es_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import type { ClientOptions } from '@elastic/elasticsearch/lib/client'; import type { ESSearchResponse, ESSearchRequest } from '@kbn/es-types'; @@ -27,6 +27,7 @@ export function getEsClient({ }, requestTimeout: 120000, auth, + Connection: HttpConnection, }); const originalSearch = client.search.bind(client); diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/anomaly_detection/get_anomaly_timeseries.ts b/x-pack/solutions/observability/plugins/apm/server/lib/anomaly_detection/get_anomaly_timeseries.ts index 32da4b6637228..00d8db1e42ab0 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/anomaly_detection/get_anomaly_timeseries.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/anomaly_detection/get_anomaly_timeseries.ts @@ -96,87 +96,85 @@ export async function getAnomalyTimeseries({ minBucketSize, }); const anomaliesResponse = await anomalySearch(mlClient.mlSystem.mlAnomalySearch, { - body: { - size: 0, - query: { - bool: { - filter: [ - ...apmMlAnomalyQuery({ - serviceName, - transactionType, - }), - ...rangeQuery(extendedStart, extendedEnd, 'timestamp'), - ...apmMlJobsQuery(mlJobs), - ], - }, + size: 0, + query: { + bool: { + filter: [ + ...apmMlAnomalyQuery({ + serviceName, + transactionType, + }), + ...rangeQuery(extendedStart, extendedEnd, 'timestamp'), + ...apmMlJobsQuery(mlJobs), + ], }, - aggs: { - by_timeseries_id: { - composite: { - size: 5000, - sources: asMutableArray([ - { - jobId: { - terms: { - field: 'job_id', - }, + }, + aggs: { + by_timeseries_id: { + composite: { + size: 5000, + sources: asMutableArray([ + { + jobId: { + terms: { + field: 'job_id', }, }, - { - detectorIndex: { - terms: { - field: 'detector_index', - }, + }, + { + detectorIndex: { + terms: { + field: 'detector_index', }, }, - { - serviceName: { - terms: { - field: 'partition_field_value', - }, + }, + { + serviceName: { + terms: { + field: 'partition_field_value', }, }, - { - transactionType: { - terms: { - field: 'by_field_value', - }, + }, + { + transactionType: { + terms: { + field: 'by_field_value', }, }, - ] as const), - }, - aggs: { - timeseries: { - date_histogram: { - field: 'timestamp', - fixed_interval: intervalString, - extended_bounds: { - min: extendedStart, - max: extendedEnd, - }, + }, + ] as const), + }, + aggs: { + timeseries: { + date_histogram: { + field: 'timestamp', + fixed_interval: intervalString, + extended_bounds: { + min: extendedStart, + max: extendedEnd, }, - aggs: { - top_anomaly: { - top_metrics: { - metrics: asMutableArray([ - { field: 'record_score' }, - { field: 'actual' }, - ] as const), - size: 1, - sort: { - record_score: 'desc', - }, + }, + aggs: { + top_anomaly: { + top_metrics: { + metrics: asMutableArray([ + { field: 'record_score' }, + { field: 'actual' }, + ] as const), + size: 1, + sort: { + record_score: 'desc', }, }, - model_lower: { - min: { - field: 'model_lower', - }, + }, + model_lower: { + min: { + field: 'model_lower', }, - model_upper: { - max: { - field: 'model_upper', - }, + }, + model_upper: { + max: { + field: 'model_upper', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts b/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts index c6689a30c7a1f..24038acff0488 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts @@ -113,7 +113,7 @@ describe('data telemetry collection tasks', () => { let arrayLength = 1000; let nextAfter: Record = { after_key: {} }; - if (params.body.aggs.transaction_metric_groups.composite.after) { + if (params.aggs.transaction_metric_groups.composite.after) { arrayLength = 250; nextAfter = {}; } @@ -307,7 +307,7 @@ describe('data telemetry collection tasks', () => { const getTime = jest.spyOn(Date.prototype, 'getTime').mockReturnValue(1594330792957); const search = jest.fn().mockImplementation((params: any) => { - const isTotalHitsQuery = params?.body?.track_total_hits; + const isTotalHitsQuery = params?.track_total_hits; return Promise.resolve( isTotalHitsQuery @@ -635,7 +635,7 @@ describe('data telemetry collection tasks', () => { it('returns cardinalities', async () => { const search = jest.fn().mockImplementation((params: any) => { - const isRumQuery = params.body.query.bool.filter.length === 2; + const isRumQuery = params.query.bool.filter.length === 2; if (isRumQuery) { return Promise.resolve({ aggregations: { @@ -879,7 +879,7 @@ describe('data telemetry collection tasks', () => { it('should return services per agent name', async () => { const search = jest.fn().mockImplementation((params: any) => { - const filter = params.body.query.bool.filter[0]; + const filter = params.query.bool.filter[0]; const queryKnownAgentNames = filter.term; const queryOtelAgentNames = filter.prefix; const queryServices = filter.exists; @@ -975,7 +975,7 @@ describe('data telemetry collection tasks', () => { 'service.runtime.version': { buckets: [{ key: '17.0.12', doc_count: 113 }] }, }; - const filter = params.body.query.bool.filter[0]; + const filter = params.query.bool.filter[0]; const queryKnownAgentNames = filter.term; const queryOtelAgentNames = filter.prefix; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts b/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts index 1c6fb8c4d6233..0f8e87c4331aa 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { getKqlFieldNamesFromExpression } from '@kbn/es-query'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { createHash } from 'crypto'; @@ -125,29 +125,27 @@ export const tasks: TelemetryTask[] = [ const params = { index: [indices.transaction], - body: { - track_total_hits: true, - size: 0, - timeout, - query: { - bool: { - filter: [ - { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, - { range: { '@timestamp': { gte: start, lt: end } } }, - ], - }, + track_total_hits: true, + size: 0, + timeout, + query: { + bool: { + filter: [ + { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, + { range: { '@timestamp': { gte: start, lt: end } } }, + ], }, - aggs: { - transaction_metric_groups: { - composite: { - ...(after ? { after } : {}), - size: 10000, - sources: sources.map((source, index) => { - return { - [index]: source, - }; - }), - }, + }, + aggs: { + transaction_metric_groups: { + composite: { + ...(after ? { after } : {}), + size: 10000, + sources: sources.map((source, index) => { + return { + [index]: source, + }; + }), }, }, }, @@ -187,20 +185,18 @@ export const tasks: TelemetryTask[] = [ const lastTransaction = ( await telemetryClient.search({ index: indices.transaction, - body: { - timeout, - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }], - }, - }, - size: 1, - track_total_hits: false, - sort: { - [AT_TIMESTAMP]: 'desc' as const, + timeout, + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }], }, - fields: [AT_TIMESTAMP], }, + size: 1, + track_total_hits: false, + sort: { + [AT_TIMESTAMP]: 'desc' as const, + }, + fields: [AT_TIMESTAMP], }) ).hits.hits[0]; @@ -300,25 +296,23 @@ export const tasks: TelemetryTask[] = [ const response = await telemetryClient.search({ index: [indices.error, indices.metric, indices.span, indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - aggs: { - [az]: { - terms: { - field: CLOUD_AVAILABILITY_ZONE, - }, + track_total_hits: false, + size: 0, + timeout, + aggs: { + [az]: { + terms: { + field: CLOUD_AVAILABILITY_ZONE, }, - [provider]: { - terms: { - field: CLOUD_PROVIDER, - }, + }, + [provider]: { + terms: { + field: CLOUD_PROVIDER, }, - [region]: { - terms: { - field: CLOUD_REGION, - }, + }, + [region]: { + terms: { + field: CLOUD_REGION, }, }, }, @@ -353,15 +347,13 @@ export const tasks: TelemetryTask[] = [ const response = await telemetryClient.search({ index: [indices.error, indices.metric, indices.span, indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - aggs: { - platform: { - terms: { - field: HOST_OS_PLATFORM, - }, + track_total_hits: false, + size: 0, + timeout, + aggs: { + platform: { + terms: { + field: HOST_OS_PLATFORM, }, }, }, @@ -385,43 +377,41 @@ export const tasks: TelemetryTask[] = [ executor: async ({ indices, telemetryClient }) => { const response = await telemetryClient.search({ index: [indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [range1d], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [range1d], }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - size: 5, - }, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, + size: 5, }, - service_environments: { - composite: { - size: 1000, - sources: asMutableArray([ - { - [SERVICE_ENVIRONMENT]: { - terms: { - field: SERVICE_ENVIRONMENT, - missing_bucket: true, - }, + }, + service_environments: { + composite: { + size: 1000, + sources: asMutableArray([ + { + [SERVICE_ENVIRONMENT]: { + terms: { + field: SERVICE_ENVIRONMENT, + missing_bucket: true, }, }, - { - [SERVICE_NAME]: { - terms: { - field: SERVICE_NAME, - }, + }, + { + [SERVICE_NAME]: { + terms: { + field: SERVICE_NAME, }, }, - ] as const), - }, + }, + ] as const), }, }, }, @@ -488,17 +478,15 @@ export const tasks: TelemetryTask[] = [ const totalHitsResponse = await telemetryClient.search({ index: indicesByProcessorEvent[processorEvent], - body: { - size: 0, - track_total_hits: true, - timeout, - query: { - bool: { - filter: [ - { term: { [PROCESSOR_EVENT]: processorEvent } }, - ...(timeRange === '1d' ? [range1d] : []), - ], - }, + size: 0, + track_total_hits: true, + timeout, + query: { + bool: { + filter: [ + { term: { [PROCESSOR_EVENT]: processorEvent } }, + ...(timeRange === '1d' ? [range1d] : []), + ], }, }, }); @@ -508,20 +496,17 @@ export const tasks: TelemetryTask[] = [ ? await telemetryClient.search({ index: indicesByProcessorEvent[processorEvent], size: 10, - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: processorEvent } }], - }, - }, - sort: { - [AT_TIMESTAMP]: 'asc', + track_total_hits: false, + timeout, + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: processorEvent } }], }, - fields: [AT_TIMESTAMP], }, + sort: { + [AT_TIMESTAMP]: 'asc', + }, + fields: [AT_TIMESTAMP], }) : null; @@ -558,11 +543,9 @@ export const tasks: TelemetryTask[] = [ executor: async ({ indices, telemetryClient }) => { const agentConfigurationCount = await telemetryClient.search({ index: APM_AGENT_CONFIGURATION_INDEX, - body: { - size: 0, - timeout, - track_total_hits: true, - }, + size: 0, + timeout, + track_total_hits: true, }); return { @@ -617,27 +600,25 @@ export const tasks: TelemetryTask[] = [ return prevJob.then(async (data) => { const response = await telemetryClient.search({ index: [indices.error, indices.span, indices.metric, indices.transaction], - body: { - size: 0, - track_total_hits: false, - timeout, - query: { - bool: { - filter: [ - { - term: { - [AGENT_NAME]: agentName, - }, + size: 0, + track_total_hits: false, + timeout, + query: { + bool: { + filter: [ + { + term: { + [AGENT_NAME]: agentName, }, - range1d, - ], - }, - }, - aggs: { - services: { - cardinality: { - field: SERVICE_NAME, }, + range1d, + ], + }, + }, + aggs: { + services: { + cardinality: { + field: SERVICE_NAME, }, }, }, @@ -655,26 +636,24 @@ export const tasks: TelemetryTask[] = [ return prevJob.then(async (accData) => { const response = await telemetryClient.search({ index: [indices.error, indices.span, indices.metric, indices.transaction], - body: { - size: 0, - track_total_hits: false, - timeout, - query: { - bool: { - filter: [{ prefix: { [AGENT_NAME]: baseAgentName } }, range1d], - }, + size: 0, + track_total_hits: false, + timeout, + query: { + bool: { + filter: [{ prefix: { [AGENT_NAME]: baseAgentName } }, range1d], }, - aggs: { - agent_name: { - terms: { - field: AGENT_NAME, - size: 1000, - }, - aggs: { - services: { - cardinality: { - field: SERVICE_NAME, - }, + }, + aggs: { + agent_name: { + terms: { + field: AGENT_NAME, + size: 1000, + }, + aggs: { + services: { + cardinality: { + field: SERVICE_NAME, }, }, }, @@ -697,24 +676,22 @@ export const tasks: TelemetryTask[] = [ const services = await telemetryClient.search({ index: [indices.error, indices.span, indices.metric, indices.transaction], - body: { - size: 0, - track_total_hits: true, - terminate_after: 1, - query: { - bool: { - filter: [ - { - exists: { - field: SERVICE_NAME, - }, + size: 0, + track_total_hits: true, + terminate_after: 1, + query: { + bool: { + filter: [ + { + exists: { + field: SERVICE_NAME, }, - range1d, - ], - }, + }, + range1d, + ], }, - timeout, }, + timeout, }); const servicesPerAgents: Record = { @@ -735,20 +712,18 @@ export const tasks: TelemetryTask[] = [ const response = await telemetryClient.search({ index: [indices.transaction, indices.span, indices.error], terminate_after: 1, - body: { - query: { - exists: { - field: 'observer.version', - }, + query: { + exists: { + field: 'observer.version', }, - track_total_hits: false, - size: 1, - timeout, - sort: { - '@timestamp': 'desc', - }, - fields: asMutableArray([OBSERVER_VERSION] as const), }, + track_total_hits: false, + size: 1, + timeout, + sort: { + '@timestamp': 'desc', + }, + fields: asMutableArray([OBSERVER_VERSION] as const), }); const event = unflattenKnownApmEventFields(response.hits.hits[0]?.fields); @@ -775,29 +750,27 @@ export const tasks: TelemetryTask[] = [ const errorGroupsCount = ( await telemetryClient.search({ index: indices.error, - body: { - size: 0, - timeout, - track_total_hits: false, - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.error } }, range1d], - }, + size: 0, + timeout, + track_total_hits: false, + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.error } }, range1d], }, - aggs: { - top_service: { - terms: { - field: SERVICE_NAME, - order: { - error_groups: 'desc', - }, - size: 1, + }, + aggs: { + top_service: { + terms: { + field: SERVICE_NAME, + order: { + error_groups: 'desc', }, - aggs: { - error_groups: { - cardinality: { - field: ERROR_GROUP_ID, - }, + size: 1, + }, + aggs: { + error_groups: { + cardinality: { + field: ERROR_GROUP_ID, }, }, }, @@ -809,29 +782,27 @@ export const tasks: TelemetryTask[] = [ const transactionGroupsCount = ( await telemetryClient.search({ index: indices.transaction, - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, range1d], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, range1d], }, - aggs: { - top_service: { - terms: { - field: SERVICE_NAME, - order: { - transaction_groups: 'desc', - }, - size: 1, + }, + aggs: { + top_service: { + terms: { + field: SERVICE_NAME, + order: { + transaction_groups: 'desc', }, - aggs: { - transaction_groups: { - cardinality: { - field: TRANSACTION_NAME, - }, + size: 1, + }, + aggs: { + transaction_groups: { + cardinality: { + field: TRANSACTION_NAME, }, }, }, @@ -843,43 +814,39 @@ export const tasks: TelemetryTask[] = [ const tracesPerDayCount = ( await telemetryClient.search({ index: indices.transaction, - body: { - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, range1d], - must_not: { - exists: { field: PARENT_ID }, - }, + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, range1d], + must_not: { + exists: { field: PARENT_ID }, }, }, - track_total_hits: true, - size: 0, - timeout, }, + track_total_hits: true, + size: 0, + timeout, }) ).hits.total.value; const servicesAndEnvironmentsCount = await telemetryClient.search({ index: [indices.transaction, indices.error, indices.metric], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [range1d], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [range1d], }, - aggs: { - service_name: { - cardinality: { - field: SERVICE_NAME, - }, + }, + aggs: { + service_name: { + cardinality: { + field: SERVICE_NAME, }, - service_environments: { - cardinality: { - field: SERVICE_ENVIRONMENT, - }, + }, + service_environments: { + cardinality: { + field: SERVICE_ENVIRONMENT, }, }, }, @@ -888,14 +855,12 @@ export const tasks: TelemetryTask[] = [ const spanDestinationServiceResourceCount = ( await telemetryClient.search({ index: indices.transaction, - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.span } }, range1d], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: ProcessorEvent.span } }, range1d], }, }, aggs: { @@ -1039,20 +1004,18 @@ export const tasks: TelemetryTask[] = [ const response = await telemetryClient.search({ index: [indices.error, indices.metric, indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [{ term: { [AGENT_NAME]: agentName } }, range1d], - }, - }, - sort: { - '@timestamp': 'desc', + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [{ term: { [AGENT_NAME]: agentName } }, range1d], }, - aggs: agentNameAggs, }, + sort: { + '@timestamp': 'desc', + }, + aggs: agentNameAggs, }); const { aggregations } = response; @@ -1149,26 +1112,24 @@ export const tasks: TelemetryTask[] = [ const response = await telemetryClient.search({ index: [indices.error, indices.metric, indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [{ prefix: { [AGENT_NAME]: baseAgentName } }, range1d], - }, - }, - sort: { - '@timestamp': 'desc', + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [{ prefix: { [AGENT_NAME]: baseAgentName } }, range1d], }, - aggs: { - agent_name: { - terms: { - field: AGENT_NAME, - size: 1000, - }, - aggs: agentNameAggs, + }, + sort: { + '@timestamp': 'desc', + }, + aggs: { + agent_name: { + terms: { + field: AGENT_NAME, + size: 1000, }, + aggs: agentNameAggs, }, }, }); @@ -1363,26 +1324,24 @@ export const tasks: TelemetryTask[] = [ const lastDayStatsResponse = await telemetryClient.search({ index: [indices.metric], expand_wildcards: 'all', - body: { - track_total_hits: false, - size: 0, - timeout, - query: range1d, - aggs: { - metricsets: { - terms: { - field: METRICSET_NAME, - }, - aggs: { - rollup_interval: { - terms: { - field: METRICSET_INTERVAL, - }, - aggs: { - metrics_value_count: { - value_count: { - field: METRICSET_INTERVAL, - }, + track_total_hits: false, + size: 0, + timeout, + query: range1d, + aggs: { + metricsets: { + terms: { + field: METRICSET_NAME, + }, + aggs: { + rollup_interval: { + terms: { + field: METRICSET_INTERVAL, + }, + aggs: { + metrics_value_count: { + value_count: { + field: METRICSET_INTERVAL, }, }, }, @@ -1501,25 +1460,23 @@ export const tasks: TelemetryTask[] = [ executor: async ({ indices, telemetryClient }) => { const allAgentsCardinalityResponse = await telemetryClient.search({ index: [indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [range1d], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [range1d], }, - aggs: { - [TRANSACTION_NAME]: { - cardinality: { - field: TRANSACTION_NAME, - }, + }, + aggs: { + [TRANSACTION_NAME]: { + cardinality: { + field: TRANSACTION_NAME, }, - [USER_AGENT_ORIGINAL]: { - cardinality: { - field: USER_AGENT_ORIGINAL, - }, + }, + [USER_AGENT_ORIGINAL]: { + cardinality: { + field: USER_AGENT_ORIGINAL, }, }, }, @@ -1527,28 +1484,26 @@ export const tasks: TelemetryTask[] = [ const rumAgentCardinalityResponse = await telemetryClient.search({ index: [indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [range1d, { terms: { [AGENT_NAME]: RUM_AGENT_NAMES } }], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [range1d, { terms: { [AGENT_NAME]: RUM_AGENT_NAMES } }], }, - aggs: { - [CLIENT_GEO_COUNTRY_ISO_CODE]: { - cardinality: { field: CLIENT_GEO_COUNTRY_ISO_CODE }, - }, - [TRANSACTION_NAME]: { - cardinality: { - field: TRANSACTION_NAME, - }, + }, + aggs: { + [CLIENT_GEO_COUNTRY_ISO_CODE]: { + cardinality: { field: CLIENT_GEO_COUNTRY_ISO_CODE }, + }, + [TRANSACTION_NAME]: { + cardinality: { + field: TRANSACTION_NAME, }, - [USER_AGENT_ORIGINAL]: { - cardinality: { - field: USER_AGENT_ORIGINAL, - }, + }, + [USER_AGENT_ORIGINAL]: { + cardinality: { + field: USER_AGENT_ORIGINAL, }, }, }, @@ -1647,104 +1602,102 @@ export const tasks: TelemetryTask[] = [ executor: async ({ indices, telemetryClient }) => { const response = await telemetryClient.search({ index: [indices.transaction], - body: { - track_total_hits: false, - size: 0, - timeout, - query: { - bool: { - filter: [ - { range: { '@timestamp': { gte: 'now-1h' } } }, - { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, - ], - }, + track_total_hits: false, + size: 0, + timeout, + query: { + bool: { + filter: [ + { range: { '@timestamp': { gte: 'now-1h' } } }, + { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, + ], }, - aggs: { - service_names: { - terms: { - field: SERVICE_NAME, - size: 2500, - }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - size: 5, - }, - aggs: { - instances: { - cardinality: { - field: SERVICE_NODE_NAME, - }, + }, + aggs: { + service_names: { + terms: { + field: SERVICE_NAME, + size: 2500, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, + size: 5, + }, + aggs: { + instances: { + cardinality: { + field: SERVICE_NODE_NAME, }, - transaction_types: { - cardinality: { - field: TRANSACTION_TYPE, - }, + }, + transaction_types: { + cardinality: { + field: TRANSACTION_TYPE, }, + }, + top_metrics: { top_metrics: { - top_metrics: { - sort: '_score', - metrics: [ - { - field: AGENT_ACTIVATION_METHOD, - }, - { - field: AGENT_NAME, - }, - { - field: AGENT_VERSION, - }, - { - field: SERVICE_LANGUAGE_NAME, - }, - { - field: SERVICE_LANGUAGE_VERSION, - }, - { - field: SERVICE_FRAMEWORK_NAME, - }, - { - field: SERVICE_FRAMEWORK_VERSION, - }, - { - field: SERVICE_RUNTIME_NAME, - }, - { - field: SERVICE_RUNTIME_VERSION, - }, - { - field: KUBERNETES_POD_NAME, - }, - { - field: CONTAINER_ID, - }, - ], - }, + sort: '_score', + metrics: [ + { + field: AGENT_ACTIVATION_METHOD, + }, + { + field: AGENT_NAME, + }, + { + field: AGENT_VERSION, + }, + { + field: SERVICE_LANGUAGE_NAME, + }, + { + field: SERVICE_LANGUAGE_VERSION, + }, + { + field: SERVICE_FRAMEWORK_NAME, + }, + { + field: SERVICE_FRAMEWORK_VERSION, + }, + { + field: SERVICE_RUNTIME_NAME, + }, + { + field: SERVICE_RUNTIME_VERSION, + }, + { + field: KUBERNETES_POD_NAME, + }, + { + field: CONTAINER_ID, + }, + ], }, - [CLOUD_REGION]: { - terms: { - field: CLOUD_REGION, - size: 5, - }, + }, + [CLOUD_REGION]: { + terms: { + field: CLOUD_REGION, + size: 5, }, - [CLOUD_PROVIDER]: { - terms: { - field: CLOUD_PROVIDER, - size: 3, - }, + }, + [CLOUD_PROVIDER]: { + terms: { + field: CLOUD_PROVIDER, + size: 3, }, - [CLOUD_AVAILABILITY_ZONE]: { - terms: { - field: CLOUD_AVAILABILITY_ZONE, - size: 5, - }, + }, + [CLOUD_AVAILABILITY_ZONE]: { + terms: { + field: CLOUD_AVAILABILITY_ZONE, + size: 5, }, - [FAAS_TRIGGER_TYPE]: { - terms: { - field: FAAS_TRIGGER_TYPE, - size: 5, - }, + }, + [FAAS_TRIGGER_TYPE]: { + terms: { + field: FAAS_TRIGGER_TYPE, + size: 5, }, }, }, @@ -1825,32 +1778,30 @@ export const tasks: TelemetryTask[] = [ executor: async ({ indices, telemetryClient }) => { const response = await telemetryClient.search({ index: [indices.transaction, indices.span, indices.error], - body: { - size: 0, - track_total_hits: false, - timeout, - query: { - bool: { - filter: [range1d], - }, + size: 0, + track_total_hits: false, + timeout, + query: { + bool: { + filter: [range1d], }, - aggs: { - top_traces: { - terms: { - field: TRACE_ID, - size: 100, - }, + }, + aggs: { + top_traces: { + terms: { + field: TRACE_ID, + size: 100, }, - max: { - max_bucket: { - buckets_path: 'top_traces>_count', - }, + }, + max: { + max_bucket: { + buckets_path: 'top_traces>_count', }, - median: { - percentiles_bucket: { - buckets_path: 'top_traces>_count', - percents: [50], - }, + }, + median: { + percentiles_bucket: { + buckets_path: 'top_traces>_count', + percents: [50], }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/telemetry_client.ts b/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/telemetry_client.ts index 80548a50e15fc..dfe1b0bcf4411 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/telemetry_client.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/apm_telemetry/telemetry_client.ts @@ -12,7 +12,9 @@ import { unwrapEsResponse } from '@kbn/observability-plugin/server'; interface RequiredSearchParams { index: string | string[]; - body: { size: number; track_total_hits: boolean | number; timeout: string }; + size: number; + track_total_hits: boolean | number; + timeout: string; } export interface IndicesStatsResponse { diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts b/x-pack/solutions/observability/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts index c5d05a928b139..1f7cc9074dfea 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { AGENT_NAME } from '../../../common/es_fields/apm'; import { RUM_AGENT_NAMES } from '../../../common/agent_name'; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts b/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts index 4263270f20474..e0389f1455058 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import objectHash from 'object-hash'; import { rangeQuery } from '@kbn/observability-plugin/server'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; @@ -86,11 +86,9 @@ export const getDestinationMap = ({ apm: { events: [ProcessorEvent.span], }, - body: { - size: 0, - track_total_hits: true, - query, - }, + size: 0, + track_total_hits: true, + query, }); const totalDocCount = hitCountResponse.hits.total.value; @@ -102,47 +100,45 @@ export const getDestinationMap = ({ apm: { events: [ProcessorEvent.span], }, - body: { - track_total_hits: false, - size: 0, - query, - aggs: { - sampling: { - random_sampler: { - ...randomSampler, - probability: samplingProbability, - }, - aggs: { - connections: { - composite: { - size: 10000, - sources: asMutableArray([ - { - dependencyName: { - terms: { field: SPAN_DESTINATION_SERVICE_RESOURCE }, - }, - }, - // make sure we get samples for both successful - // and failed calls - { eventOutcome: { terms: { field: EVENT_OUTCOME } } }, - ] as const), - }, - aggs: { - sample: { - top_metrics: { - size: 1, - metrics: asMutableArray([ - { field: SPAN_TYPE }, - { field: SPAN_SUBTYPE }, - { field: SPAN_ID }, - ] as const), - sort: [ - { - '@timestamp': 'asc' as const, - }, - ], + track_total_hits: false, + size: 0, + query, + aggs: { + sampling: { + random_sampler: { + ...randomSampler, + probability: samplingProbability, + }, + aggs: { + connections: { + composite: { + size: 10000, + sources: asMutableArray([ + { + dependencyName: { + terms: { field: SPAN_DESTINATION_SERVICE_RESOURCE }, }, }, + // make sure we get samples for both successful + // and failed calls + { eventOutcome: { terms: { field: EVENT_OUTCOME } } }, + ] as const), + }, + aggs: { + sample: { + top_metrics: { + size: 1, + metrics: asMutableArray([ + { field: SPAN_TYPE }, + { field: SPAN_SUBTYPE }, + { field: SPAN_ID }, + ] as const), + sort: [ + { + '@timestamp': 'asc' as const, + }, + ], + }, }, }, }, @@ -170,24 +166,22 @@ export const getDestinationMap = ({ apm: { events: [ProcessorEvent.transaction], }, - body: { - track_total_hits: false, - query: { - bool: { - filter: [ - { - terms: { - [PARENT_ID]: Array.from(destinationsBySpanId.keys()), - }, + track_total_hits: false, + query: { + bool: { + filter: [ + { + terms: { + [PARENT_ID]: Array.from(destinationsBySpanId.keys()), }, - // add a 5m buffer at the end of the time range for long running spans - ...rangeQuery(startWithOffset, endWithOffset + 1000 * 1000 * 60 * 5), - ], - }, + }, + // add a 5m buffer at the end of the time range for long running spans + ...rangeQuery(startWithOffset, endWithOffset + 1000 * 1000 * 60 * 5), + ], }, - size: destinationsBySpanId.size, - fields: asMutableArray([SERVICE_NAME, SERVICE_ENVIRONMENT, AGENT_NAME, PARENT_ID] as const), }, + size: destinationsBySpanId.size, + fields: asMutableArray([SERVICE_NAME, SERVICE_ENVIRONMENT, AGENT_NAME, PARENT_ID] as const), }); transactionResponse.hits.hits.forEach((hit) => { diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts b/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts index a583e4de02c92..8f55d921ec63d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts @@ -7,7 +7,7 @@ import { sum } from 'lodash'; import objectHash from 'object-hash'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { rangeQuery } from '@kbn/observability-plugin/server'; import type { AgentName } from '../../../../typings/es_schemas/ui/fields/agent'; import { getOffsetInMs } from '../../../../common/utils/get_offset_in_ms'; @@ -135,107 +135,105 @@ async function getConnectionStats({ }, ], }, - body: { - track_total_hits: true, - size: 0, - query: { - bool: { - filter: [ - ...filter, - ...getDocumentTypeFilterForServiceDestinationStatistics(true), - ...rangeQuery(startWithOffset, endWithOffset), - ...excludeRumExitSpansQuery(), - ], - }, + track_total_hits: true, + size: 0, + query: { + bool: { + filter: [ + ...filter, + ...getDocumentTypeFilterForServiceDestinationStatistics(true), + ...rangeQuery(startWithOffset, endWithOffset), + ...excludeRumExitSpansQuery(), + ], }, - aggs: { - connections: { - composite: { - size: MAX_ITEMS, - sources: asMutableArray([ - { - serviceName: { - terms: { - field: SERVICE_NAME, - }, + }, + aggs: { + connections: { + composite: { + size: MAX_ITEMS, + sources: asMutableArray([ + { + serviceName: { + terms: { + field: SERVICE_NAME, }, }, - { - dependencyName: { - terms: { - field: SPAN_DESTINATION_SERVICE_RESOURCE, - }, + }, + { + dependencyName: { + terms: { + field: SPAN_DESTINATION_SERVICE_RESOURCE, }, }, - ] as const), - }, - aggs: { - sample: { - top_metrics: { - size: 1, - metrics: asMutableArray([ - { - field: SERVICE_ENVIRONMENT, - }, - { - field: AGENT_NAME, - }, - { - field: SPAN_TYPE, - }, - { - field: SPAN_SUBTYPE, - }, - ] as const), - sort: { - '@timestamp': 'desc', + }, + ] as const), + }, + aggs: { + sample: { + top_metrics: { + size: 1, + metrics: asMutableArray([ + { + field: SERVICE_ENVIRONMENT, }, + { + field: AGENT_NAME, + }, + { + field: SPAN_TYPE, + }, + { + field: SPAN_SUBTYPE, + }, + ] as const), + sort: { + '@timestamp': 'desc', }, }, - total_latency_sum: { - sum: { - field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_SUM, - }, + }, + total_latency_sum: { + sum: { + field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_SUM, + }, + }, + total_latency_count: { + sum: { + field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT, }, - total_latency_count: { - sum: { - field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT, + }, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: getBucketSize({ + start: startWithOffset, + end: endWithOffset, + numBuckets, + minBucketSize: 60, + }).intervalString, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, }, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: getBucketSize({ - start: startWithOffset, - end: endWithOffset, - numBuckets, - minBucketSize: 60, - }).intervalString, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, + aggs: { + latency_sum: { + sum: { + field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_SUM, }, }, - aggs: { - latency_sum: { - sum: { - field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_SUM, - }, + count: { + sum: { + field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT, }, - count: { - sum: { - field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT, - }, + }, + [EVENT_OUTCOME]: { + terms: { + field: EVENT_OUTCOME, }, - [EVENT_OUTCOME]: { - terms: { - field: EVENT_OUTCOME, - }, - aggs: { - count: { - sum: { - field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT, - }, + aggs: { + count: { + sum: { + field: SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/index.ts b/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/index.ts index 82e8dd5d1d950..5833c1518fd23 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/connections/get_connection_stats/index.ts @@ -7,7 +7,7 @@ import type { ValuesType } from 'utility-types'; import { merge } from 'lodash'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { joinByKey } from '../../../../common/utils/join_by_key'; import { getStats } from './get_stats'; import { getDestinationMap } from './get_destination_map'; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client.ts b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client.ts index 2055ce0fced68..777715bee2ec9 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { InferSearchResponseOf } from '@kbn/es-types'; import type { KibanaRequest } from '@kbn/core/server'; import type { ElasticsearchClient } from '@kbn/core/server'; @@ -111,9 +111,7 @@ export async function createEntitiesESClient({ index: [SERVICE_ENTITIES_LATEST_ALIAS], ignore_unavailable: true, }, - { - ...params.body, - }, + params, ]; return searchParams; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts index e65c8b21b3f31..32538b5fe4f9c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { unwrapEsResponse } from '@kbn/observability-plugin/server'; import type { ESSearchResponse, ESSearchRequest } from '@kbn/es-types'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/get_apm_alerts_client.ts b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/get_apm_alerts_client.ts index f0084151dfce0..1e30e99179cd5 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/get_apm_alerts_client.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/get_apm_alerts_client.ts @@ -6,7 +6,7 @@ */ import { isEmpty } from 'lodash'; -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { InferSearchResponseOf } from '@kbn/es-types'; import type { ParsedTechnicalFields } from '@kbn/rule-registry-plugin/common'; import type { DataTier } from '@kbn/observability-shared-plugin/common'; @@ -22,6 +22,8 @@ export type ApmAlertsRequiredParams = ESSearchRequest & { size: number; track_total_hits: boolean | number; query?: estypes.QueryDslQueryContainer; + sort?: estypes.SortOptions[]; + _source?: string[] | false; }; export async function getApmAlertsClient({ diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/spans/get_is_using_service_destination_metrics.ts b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/spans/get_is_using_service_destination_metrics.ts index 7c6ad46b63db2..9192f8dfaccbf 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/spans/get_is_using_service_destination_metrics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/spans/get_is_using_service_destination_metrics.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { kqlQuery, rangeQuery } from '@kbn/observability-plugin/server'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { getDocumentTypeFilterForServiceDestinationStatistics } from '@kbn/apm-data-access-plugin/server/utils'; @@ -55,19 +55,17 @@ export async function getIsUsingServiceDestinationMetrics({ apm: { events: [getProcessorEventForServiceDestinationStatistics(true)], }, - body: { - track_total_hits: 1, - size: 0, - terminate_after: 1, - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - ...kqlQuery(kuery), - ...getDocumentTypeFilterForServiceDestinationStatistics(true), - ...(query ? [query] : []), - ], - }, + track_total_hits: 1, + size: 0, + terminate_after: 1, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + ...kqlQuery(kuery), + ...getDocumentTypeFilterForServiceDestinationStatistics(true), + ...(query ? [query] : []), + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap index 192df5cc8eb3a..18dcc5326c64c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap @@ -7,34 +7,32 @@ Object { "metric", ], }, - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "transaction.duration.histogram", - }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "transaction.duration.histogram", }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "proccessor.event": "transaction", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "proccessor.event": "transaction", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, - "terminate_after": 1, - "track_total_hits": 1, }, + "size": 0, + "terminate_after": 1, + "track_total_hits": 1, } `; @@ -45,22 +43,20 @@ Object { "metric", ], }, - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "transaction.duration.histogram", - }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "transaction.duration.histogram", }, - ], - }, + }, + ], }, - "size": 0, - "terminate_after": 1, - "track_total_hits": 1, }, + "size": 0, + "terminate_after": 1, + "track_total_hits": 1, } `; @@ -74,22 +70,20 @@ Array [ "metric", ], }, - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "transaction.duration.histogram", - }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "transaction.duration.histogram", }, - ], - }, + }, + ], }, - "size": 0, - "terminate_after": 1, - "track_total_hits": 1, }, + "size": 0, + "terminate_after": 1, + "track_total_hits": 1, }, ], Array [ @@ -103,16 +97,14 @@ Array [ }, ], }, - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [], - }, + "query": Object { + "bool": Object { + "filter": Array [], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, "terminate_after": 1, + "track_total_hits": 1, }, ], ] diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts index 38b8821ef956e..650e0ede9fa31 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts @@ -70,13 +70,11 @@ async function getHasTransactions({ }, ], }, - body: { - track_total_hits: 1, - size: 0, - query: { - bool: { - filter: [...(start && end ? rangeQuery(start, end) : []), ...kqlQuery(kuery)], - }, + track_total_hits: 1, + size: 0, + query: { + bool: { + filter: [...(start && end ? rangeQuery(start, end) : []), ...kqlQuery(kuery)], }, }, terminate_after: 1, diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/index.ts b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/index.ts index b59001418a8f3..ed2c9d8dca749 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/helpers/transactions/index.ts @@ -7,7 +7,7 @@ import { kqlQuery, rangeQuery } from '@kbn/observability-plugin/server'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SearchAggregatedTransactionSetting } from '../../../../common/aggregated_transactions'; import { TRANSACTION_DURATION, @@ -37,18 +37,16 @@ export async function getHasTransactionsEvents({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: 1, - terminate_after: 1, - size: 0, - query: { - bool: { - filter: [ - { exists: { field: TRANSACTION_DURATION_HISTOGRAM } }, - ...(start && end ? rangeQuery(start, end) : []), - ...kqlQuery(kuery), - ], - }, + track_total_hits: 1, + terminate_after: 1, + size: 0, + query: { + bool: { + filter: [ + { exists: { field: TRANSACTION_DURATION_HISTOGRAM } }, + ...(start && end ? rangeQuery(start, end) : []), + ...kqlQuery(kuery), + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query.ts b/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query.ts index 560b442e1eb90..ef61194ffc59d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { kqlQuery } from '@kbn/observability-plugin/server'; import type { ServiceGroup } from '../../common/service_groups'; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query_with_overflow.ts b/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query_with_overflow.ts index 12f9a2d9978fc..cad7ad940611e 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query_with_overflow.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/service_group_query_with_overflow.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { kqlQuery, termQuery } from '@kbn/observability-plugin/server'; import { SERVICE_NAME } from '../../common/es_fields/apm'; import type { ServiceGroup } from '../../common/service_groups'; diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_coldstart_rate.ts b/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_coldstart_rate.ts index e61b30341c805..bbbf2aa77873a 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_coldstart_rate.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_coldstart_rate.ts @@ -78,26 +78,24 @@ export async function getColdstartRate({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 0, - query: { bool: { filter } }, - aggs: { - coldstartStates, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: getBucketSizeForAggregatedTransactions({ - start: startWithOffset, - end: endWithOffset, - searchAggregatedTransactions, - }).intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs: { - coldstartStates, - }, + track_total_hits: false, + size: 0, + query: { bool: { filter } }, + aggs: { + coldstartStates, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: getBucketSizeForAggregatedTransactions({ + start: startWithOffset, + end: endWithOffset, + searchAggregatedTransactions, + }).intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, + }, + aggs: { + coldstartStates, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_failed_transaction_rate.ts b/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_failed_transaction_rate.ts index 6acfc4e548730..167aef0fb1266 100644 --- a/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_failed_transaction_rate.ts +++ b/x-pack/solutions/observability/plugins/apm/server/lib/transaction_groups/get_failed_transaction_rate.ts @@ -74,22 +74,20 @@ export async function getFailedTransactionRate({ apm: { sources: [{ documentType, rollupInterval }], }, - body: { - track_total_hits: false, - size: 0, - query: { bool: { filter, must_not: mustNot } }, - aggs: { - ...outcomes, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: `${bucketSizeInSeconds}s`, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs: { - ...outcomes, - }, + track_total_hits: false, + size: 0, + query: { bool: { filter, must_not: mustNot } }, + aggs: { + ...outcomes, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: `${bucketSizeInSeconds}s`, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, + }, + aggs: { + ...outcomes, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agent_instances.ts b/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agent_instances.ts index ffd1035d01739..d9a4b2401a61c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agent_instances.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agent_instances.ts @@ -46,48 +46,46 @@ export async function getAgentInstances({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - exists: { - field: AGENT_NAME, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + exists: { + field: AGENT_NAME, }, - { - exists: { - field: AGENT_VERSION, - }, + }, + { + exists: { + field: AGENT_VERSION, }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...(serviceName ? termQuery(SERVICE_NAME, serviceName) : []), - ], - }, - }, - aggs: { - serviceNodes: { - terms: { - field: SERVICE_NODE_NAME, - missing: SERVICE_NODE_NAME_MISSING, - size: MAX_NUMBER_OF_SERVICE_NODES, }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...(serviceName ? termQuery(SERVICE_NAME, serviceName) : []), + ], + }, + }, + aggs: { + serviceNodes: { + terms: { + field: SERVICE_NODE_NAME, + missing: SERVICE_NODE_NAME_MISSING, + size: MAX_NUMBER_OF_SERVICE_NODES, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, }, - sample: { - top_metrics: { - metrics: [{ field: AGENT_VERSION } as const], - sort: { - '@timestamp': 'desc' as const, - }, + }, + sample: { + top_metrics: { + metrics: [{ field: AGENT_VERSION } as const], + sort: { + '@timestamp': 'desc' as const, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agents_items.ts b/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agents_items.ts index 364251978dec5..a910e147a0fed 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agents_items.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/agent_explorer/get_agents_items.ts @@ -47,67 +47,65 @@ export async function getAgentsItems({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - exists: { - field: AGENT_NAME, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + exists: { + field: AGENT_NAME, }, - { - exists: { - field: AGENT_VERSION, - }, + }, + { + exists: { + field: AGENT_VERSION, }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...(serviceName ? termQuery(SERVICE_NAME, serviceName) : []), - ...(agentLanguage ? termQuery(SERVICE_LANGUAGE_NAME, agentLanguage) : []), - ], - }, + }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...(serviceName ? termQuery(SERVICE_NAME, serviceName) : []), + ...(agentLanguage ? termQuery(SERVICE_LANGUAGE_NAME, agentLanguage) : []), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: MAX_NUMBER_OF_SERVICES, - }, - aggs: { - instances: { - cardinality: { - field: SERVICE_NODE_NAME, - }, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: MAX_NUMBER_OF_SERVICES, + }, + aggs: { + instances: { + cardinality: { + field: SERVICE_NODE_NAME, }, - agentTelemetryAutoVersions: { - terms: { - field: LABEL_TELEMETRY_AUTO_VERSION, - }, + }, + agentTelemetryAutoVersions: { + terms: { + field: LABEL_TELEMETRY_AUTO_VERSION, }, - agentVersions: { - terms: { - field: AGENT_VERSION, - }, + }, + agentVersions: { + terms: { + field: AGENT_VERSION, }, - sample: { - top_metrics: { - metrics: [{ field: AGENT_NAME } as const], - sort: { - '@timestamp': 'desc' as const, - }, + }, + sample: { + top_metrics: { + metrics: [{ field: AGENT_NAME } as const], + sort: { + '@timestamp': 'desc' as const, }, }, - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - }, + }, + environments: { + terms: { + field: SERVICE_ENVIRONMENT, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/create_agent_key.ts b/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/create_agent_key.ts index c0597ebf59593..a7d109aadd721 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/create_agent_key.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/create_agent_key.ts @@ -43,10 +43,8 @@ export async function createAgentKey({ has_all_requested: hasRequiredPrivileges, cluster: clusterPrivileges, } = await coreContext.elasticsearch.client.asCurrentUser.security.hasPrivileges({ - body: { - application: [application], - cluster: CLUSTER_PRIVILEGES, - }, + application: [application], + cluster: CLUSTER_PRIVILEGES, }); if (!hasRequiredPrivileges) { @@ -96,9 +94,7 @@ export async function createAgentKey({ }, }; - const agentKey = await coreContext.elasticsearch.client.asCurrentUser.security.createApiKey({ - body, - }); + const agentKey = await coreContext.elasticsearch.client.asCurrentUser.security.createApiKey(body); return { agentKey, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts b/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts index 4543705ef43fc..4a11ed24dec64 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts @@ -24,9 +24,7 @@ export async function getAgentKeysPrivileges({ const esClient = (await context.core).elasticsearch.client; const [securityHasPrivilegesResponse, areApiKeysEnabled] = await Promise.all([ esClient.asCurrentUser.security.hasPrivileges({ - body: { - cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key'], - }, + cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key'], }), coreStart.security.authc.apiKeys.areAPIKeysEnabled(), ]); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts b/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts index 17317e7e26e31..0283292905ee5 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts @@ -22,7 +22,8 @@ export async function invalidateAgentKey({ const esClient = (await context.core).elasticsearch.client; const { invalidated_api_keys: invalidatedAgentKeys } = await esClient.asCurrentUser.security.invalidateApiKey({ - body: { ids: [id], owner: !isAdmin }, + ids: [id], + owner: !isAdmin, }); return { diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.test.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.test.ts index 757b199940547..f99fe106a7630 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.test.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.test.ts @@ -18,12 +18,10 @@ describe('alertingEsClient', () => { let uiSettingsClientMock: jest.Mocked; const params = { - body: { - size: 10, - track_total_hits: true, - query: { - match: { field: 'value' }, - }, + size: 10, + track_total_hits: true, + query: { + match: { field: 'value' }, }, }; @@ -72,7 +70,7 @@ describe('alertingEsClient', () => { const searchParams = scopedClusterClientMock.asCurrentUser.search.mock .calls[0][0] as APMEventESSearchRequestParams; - expect(searchParams.body?.query).toEqual({ match: { field: 'value' } }); + expect(searchParams.query).toEqual({ match: { field: 'value' } }); }); it('should call search with filters containing excluded data tiers', async () => { @@ -83,7 +81,7 @@ describe('alertingEsClient', () => { const searchParams = scopedClusterClientMock.asCurrentUser.search.mock .calls[0][0] as APMEventESSearchRequestParams; - expect(searchParams.body?.query?.bool).toEqual({ + expect(searchParams.query?.bool).toEqual({ must: [ { match: { field: 'value' } }, { bool: { must_not: [{ terms: { _tier: ['data_warm', 'data_cold'] } }] } }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.ts index d590f808149a3..c307462ea2fcd 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/alerting_es_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { ESSearchResponse } from '@kbn/es-types'; import type { RuleExecutorServices } from '@kbn/alerting-plugin/server'; import type { IUiSettingsClient } from '@kbn/core/server'; @@ -14,7 +14,8 @@ import { getDataTierFilterCombined } from '@kbn/apm-data-access-plugin/server/ut import { searchExcludedDataTiers } from '@kbn/observability-plugin/common/ui_settings_keys'; export type APMEventESSearchRequestParams = ESSearchRequest & { - body: { size: number; track_total_hits: boolean | number }; + size: number; + track_total_hits: boolean | number; }; export async function alertingEsClient({ @@ -30,13 +31,10 @@ export async function alertingEsClient job.jobId); const anomalySearchParams = { - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { result_type: 'record' } }, - { terms: { job_id: jobIds } }, - { term: { is_interim: false } }, - { - range: { - timestamp: { - gte: dateStart, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { result_type: 'record' } }, + { terms: { job_id: jobIds } }, + { term: { is_interim: false } }, + { + range: { + timestamp: { + gte: dateStart, }, }, - ...termQuery('partition_field_value', ruleParams.serviceName, { - queryEmptyString: false, - }), - ...termQuery('by_field_value', ruleParams.transactionType, { - queryEmptyString: false, - }), - ...termsQuery( - 'detector_index', - ...(ruleParams.anomalyDetectorTypes?.map((type) => - getAnomalyDetectorIndex(type) - ) ?? []) - ), - ] as QueryDslQueryContainer[], - }, - }, - aggs: { - anomaly_groups: { - multi_terms: { - terms: [ - { field: 'partition_field_value' }, - { field: 'by_field_value' }, - { field: 'job_id' }, - { field: 'detector_index' }, - ], - size: 1000, - order: { 'latest_score.record_score': 'desc' as const }, }, - aggs: { - latest_score: { - top_metrics: { - metrics: asMutableArray([ - { field: 'record_score' }, - { field: 'partition_field_value' }, - { field: 'by_field_value' }, - { field: 'job_id' }, - { field: 'timestamp' }, - { field: 'bucket_span' }, - { field: 'detector_index' }, - ] as const), - sort: { - timestamp: 'desc' as const, - }, + ...termQuery('partition_field_value', ruleParams.serviceName, { + queryEmptyString: false, + }), + ...termQuery('by_field_value', ruleParams.transactionType, { + queryEmptyString: false, + }), + ...termsQuery( + 'detector_index', + ...(ruleParams.anomalyDetectorTypes?.map((type) => getAnomalyDetectorIndex(type)) ?? + []) + ), + ] as QueryDslQueryContainer[], + }, + }, + aggs: { + anomaly_groups: { + multi_terms: { + terms: [ + { field: 'partition_field_value' }, + { field: 'by_field_value' }, + { field: 'job_id' }, + { field: 'detector_index' }, + ], + size: 1000, + order: { 'latest_score.record_score': 'desc' as const }, + }, + aggs: { + latest_score: { + top_metrics: { + metrics: asMutableArray([ + { field: 'record_score' }, + { field: 'partition_field_value' }, + { field: 'by_field_value' }, + { field: 'job_id' }, + { field: 'timestamp' }, + { field: 'bucket_span' }, + { field: 'detector_index' }, + ] as const), + sort: { + timestamp: 'desc' as const, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/get_error_count_chart_preview.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/get_error_count_chart_preview.ts index 38ba2c052aca9..bfc564e32411c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/get_error_count_chart_preview.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/get_error_count_chart_preview.ts @@ -84,7 +84,10 @@ export async function getTransactionErrorCountChartPreview({ const params = { apm: { events: [ProcessorEvent.error] }, - body: { size: 0, track_total_hits: false, query, aggs }, + size: 0, + track_total_hits: false, + query, + aggs, }; const resp = await apmEventClient.search('get_error_count_chart_preview', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/register_error_count_rule_type.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/register_error_count_rule_type.ts index e0670fc7c1667..f3db00f0433b5 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/register_error_count_rule_type.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/error_count/register_error_count_rule_type.ts @@ -154,34 +154,32 @@ export function registerErrorCountRuleType({ const searchParams = { index: indices.error, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: dateStart, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: dateStart, }, }, - { term: { [PROCESSOR_EVENT]: ProcessorEvent.error } }, - ...termFilterQuery, - ...getParsedFilterQuery(ruleParams.searchConfiguration?.query?.query as string), - ], - }, - }, - aggs: { - error_counts: { - multi_terms: { - terms: getGroupByTerms(allGroupByFields), - size: 1000, - order: { _count: 'desc' as const }, }, - aggs: getApmAlertSourceFieldsAgg(), + { term: { [PROCESSOR_EVENT]: ProcessorEvent.error } }, + ...termFilterQuery, + ...getParsedFilterQuery(ruleParams.searchConfiguration?.query?.query as string), + ], + }, + }, + aggs: { + error_counts: { + multi_terms: { + terms: getGroupByTerms(allGroupByFields), + size: 1000, + order: { _count: 'desc' as const }, }, + aggs: getApmAlertSourceFieldsAgg(), }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/get_transaction_duration_chart_preview.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/get_transaction_duration_chart_preview.ts index 797df1945619c..dae1591bf5167 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/get_transaction_duration_chart_preview.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/get_transaction_duration_chart_preview.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { getParsedFilterQuery, rangeQuery, termQuery } from '@kbn/observability-plugin/server'; import { ApmRuleType } from '@kbn/rule-data-utils'; import { AggregationType } from '../../../../../common/rules/apm_rule_types'; @@ -119,7 +119,10 @@ export async function getTransactionDurationChartPreview({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { size: 0, track_total_hits: false, query, aggs }, + size: 0, + track_total_hits: false, + query, + aggs, }; const resp = await apmEventClient.search('get_transaction_duration_chart_preview', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/register_transaction_duration_rule_type.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/register_transaction_duration_rule_type.ts index 7d1af451d54ce..b75f2d01fa4b2 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/register_transaction_duration_rule_type.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_duration/register_transaction_duration_rule_type.ts @@ -6,7 +6,7 @@ */ import { DEFAULT_APP_CATEGORIES } from '@kbn/core/server'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { GetViewInAppRelativeUrlFnOpts, ActionGroupIdsOf, @@ -179,40 +179,38 @@ export function registerTransactionDurationRuleType({ const searchParams = { index, - body: { - track_total_hits: false, - size: 0, - _source: false as const, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: dateStart, - }, + track_total_hits: false, + size: 0, + _source: false as const, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: dateStart, }, }, - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - ...termFilterQuery, - ...getParsedFilterQuery(ruleParams.searchConfiguration?.query?.query as string), - ] as QueryDslQueryContainer[], - }, - }, - aggs: { - series: { - multi_terms: { - terms: [...getGroupByTerms(allGroupByFields)], - size: 1000, - ...getMultiTermsSortOrder(ruleParams.aggregationType), - }, - aggs: { - ...averageOrPercentileAgg({ - aggregationType: ruleParams.aggregationType, - transactionDurationField: field, - }), - ...getApmAlertSourceFieldsAgg(), }, + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + ...termFilterQuery, + ...getParsedFilterQuery(ruleParams.searchConfiguration?.query?.query as string), + ] as QueryDslQueryContainer[], + }, + }, + aggs: { + series: { + multi_terms: { + terms: [...getGroupByTerms(allGroupByFields)], + size: 1000, + ...getMultiTermsSortOrder(ruleParams.aggregationType), + }, + aggs: { + ...averageOrPercentileAgg({ + aggregationType: ruleParams.aggregationType, + transactionDurationField: field, + }), + ...getApmAlertSourceFieldsAgg(), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/get_transaction_error_rate_chart_preview.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/get_transaction_error_rate_chart_preview.ts index 7f7a6ffdf4186..72a8b630479bd 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/get_transaction_error_rate_chart_preview.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/get_transaction_error_rate_chart_preview.ts @@ -76,46 +76,44 @@ export async function getTransactionErrorRateChartPreview({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termFilterQuery, - ...getParsedFilterQuery(searchConfiguration?.query?.query as string), - ...rangeQuery(start, end), - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - { - terms: { - [EVENT_OUTCOME]: [EventOutcome.failure, EventOutcome.success], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termFilterQuery, + ...getParsedFilterQuery(searchConfiguration?.query?.query as string), + ...rangeQuery(start, end), + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + { + terms: { + [EVENT_OUTCOME]: [EventOutcome.failure, EventOutcome.success], }, - ], - }, - }, - aggs: { - series: { - multi_terms: { - terms: getGroupByTerms(allGroupByFields), - size: 1000, - order: { _count: 'desc' as const }, }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: interval, - extended_bounds: { - min: start, - max: end, - }, + ], + }, + }, + aggs: { + series: { + multi_terms: { + terms: getGroupByTerms(allGroupByFields), + size: 1000, + order: { _count: 'desc' as const }, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: interval, + extended_bounds: { + min: start, + max: end, }, - aggs: { - outcomes: { - terms: { - field: EVENT_OUTCOME, - }, + }, + aggs: { + outcomes: { + terms: { + field: EVENT_OUTCOME, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/register_transaction_error_rate_rule_type.ts b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/register_transaction_error_rate_rule_type.ts index f2a1c633dc4dd..7857872d2954a 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/register_transaction_error_rate_rule_type.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/alerts/rule_types/transaction_error_rate/register_transaction_error_rate_rule_type.ts @@ -175,44 +175,42 @@ export function registerTransactionErrorRateRuleType({ const searchParams = { index, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: dateStart, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: dateStart, }, }, - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - { - terms: { - [EVENT_OUTCOME]: [EventOutcome.failure, EventOutcome.success], - }, + }, + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + { + terms: { + [EVENT_OUTCOME]: [EventOutcome.failure, EventOutcome.success], }, - ...termFilterQuery, - ...getParsedFilterQuery(ruleParams.searchConfiguration?.query?.query as string), - ], - }, - }, - aggs: { - series: { - multi_terms: { - terms: [...getGroupByTerms(allGroupByFields)], - size: 1000, - order: { _count: 'desc' as const }, }, - aggs: { - outcomes: { - terms: { - field: EVENT_OUTCOME, - }, - aggs: getApmAlertSourceFieldsAgg(), + ...termFilterQuery, + ...getParsedFilterQuery(ruleParams.searchConfiguration?.query?.query as string), + ], + }, + }, + aggs: { + series: { + multi_terms: { + terms: [...getGroupByTerms(allGroupByFields)], + size: 1000, + order: { _count: 'desc' as const }, + }, + aggs: { + outcomes: { + terms: { + field: EVENT_OUTCOME, }, + aggs: getApmAlertSourceFieldsAgg(), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_service_summary/get_anomalies.ts b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_service_summary/get_anomalies.ts index e7b3542572087..8f96b421c066d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_service_summary/get_anomalies.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_service_summary/get_anomalies.ts @@ -56,84 +56,82 @@ export async function getAnomalies({ } const anomaliesResponse = await anomalySearch(mlClient.mlSystem.mlAnomalySearch, { - body: { - size: 0, - query: { - bool: { - filter: [ - ...apmMlAnomalyQuery({ serviceName, transactionType }), - ...rangeQuery(start, end, 'timestamp'), - ...apmMlJobsQuery(mlJobs), - ], - }, + size: 0, + query: { + bool: { + filter: [ + ...apmMlAnomalyQuery({ serviceName, transactionType }), + ...rangeQuery(start, end, 'timestamp'), + ...apmMlJobsQuery(mlJobs), + ], }, - aggs: { - by_timeseries_id: { - composite: { - size: 5000, - sources: asMutableArray([ - { - jobId: { - terms: { - field: 'job_id', - }, + }, + aggs: { + by_timeseries_id: { + composite: { + size: 5000, + sources: asMutableArray([ + { + jobId: { + terms: { + field: 'job_id', }, }, - { - detectorIndex: { - terms: { - field: 'detector_index', - }, + }, + { + detectorIndex: { + terms: { + field: 'detector_index', }, }, - { - serviceName: { - terms: { - field: 'partition_field_value', - }, + }, + { + serviceName: { + terms: { + field: 'partition_field_value', }, }, - { - transactionType: { - terms: { - field: 'by_field_value', - }, + }, + { + transactionType: { + terms: { + field: 'by_field_value', }, }, - ] as const), - }, - aggs: { - record_scores: { - filter: { - term: { - result_type: 'record', - }, + }, + ] as const), + }, + aggs: { + record_scores: { + filter: { + term: { + result_type: 'record', }, - aggs: { - top_anomaly: { - top_metrics: { - metrics: asMutableArray([ - { field: 'record_score' }, - { field: 'actual' }, - { field: 'timestamp' }, - ] as const), - size: 1, - sort: { - record_score: 'desc', - }, + }, + aggs: { + top_anomaly: { + top_metrics: { + metrics: asMutableArray([ + { field: 'record_score' }, + { field: 'actual' }, + { field: 'timestamp' }, + ] as const), + size: 1, + sort: { + record_score: 'desc', }, }, }, }, - model_lower: { - min: { - field: 'model_lower', - }, + }, + model_lower: { + min: { + field: 'model_lower', }, - model_upper: { - max: { - field: 'model_upper', - }, + }, + model_upper: { + max: { + field: 'model_upper', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_timeseries/fetch_timeseries.ts b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_timeseries/fetch_timeseries.ts index 5f0577ac163de..83ec36c1b5616 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_timeseries/fetch_timeseries.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_apm_timeseries/fetch_timeseries.ts @@ -72,44 +72,42 @@ export async function fetchSeries({ apm: { sources: [{ documentType, rollupInterval }], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter, - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter, }, - aggs: { - groups: { - ...(groupByFields.length === 1 - ? { - terms: { - size: 20, - field: groupByFields[0], - }, - } - : { - multi_terms: { - size: 20, - terms: groupByFields.map((field) => ({ field })), - }, - }), - aggs: { - ...aggs, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: start, max: end }, + }, + aggs: { + groups: { + ...(groupByFields.length === 1 + ? { + terms: { + size: 20, + field: groupByFields[0], + }, + } + : { + multi_terms: { + size: 20, + terms: groupByFields.map((field) => ({ field })), }, - aggs, + }), + aggs: { + ...aggs, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: start, max: end }, }, + aggs, + }, + change_point: { change_point: { - change_point: { - buckets_path: 'timeseries>value', - }, + buckets_path: 'timeseries>value', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_container_id_from_signals.ts b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_container_id_from_signals.ts index c7de1d41a863f..4e2d5cf26f2f5 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_container_id_from_signals.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_container_id_from_signals.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import type { CoreRequestHandlerContext } from '@kbn/core-http-request-handler-context-server'; import { rangeQuery, typedSearch } from '@kbn/observability-plugin/server/utils/queries'; @@ -47,7 +47,7 @@ export async function getContainerIdFromSignals({ const start = moment(query.alert_started_at).subtract(30, 'minutes').valueOf(); const end = moment(query.alert_started_at).valueOf(); - const params: APMEventESSearchRequest['body'] = { + const params: Omit = { _source: ['container.id'], terminate_after: 1, size: 1, @@ -79,7 +79,7 @@ async function getContainerIdFromLogs({ esClient, logSourcesService, }: { - params: ESSearchRequest['body']; + params: ESSearchRequest; esClient: ElasticsearchClient; logSourcesService: LogSourcesService; }) { @@ -100,7 +100,7 @@ async function getContainerIdFromTraces({ params, apmEventClient, }: { - params: APMEventESSearchRequest['body']; + params: Omit; apmEventClient: APMEventClient; }) { const requiredFields = asMutableArray([CONTAINER_ID] as const); @@ -113,7 +113,8 @@ async function getContainerIdFromTraces({ }, ], }, - body: { ...params, fields: requiredFields }, + ...params, + fields: requiredFields, }); const event = unflattenKnownApmEventFields(maybe(res.hits.hits[0])?.fields, requiredFields); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_downstream_dependency_name.ts b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_downstream_dependency_name.ts index f48667214a29d..20555f6ffa061 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_downstream_dependency_name.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_downstream_dependency_name.ts @@ -40,22 +40,20 @@ export async function getDownstreamServiceResource({ }, ], }, - body: { - track_total_hits: false, - size: 1, - _source: ['span.destination.service'], - query: { - bool: { - filter: [ - ...termQuery(TRACE_ID, traceId), - ...termQuery(EVENT_OUTCOME, 'failure'), - ...rangeQuery(start, end), - { exists: { field: SPAN_DESTINATION_SERVICE_RESOURCE } }, - ], - }, + track_total_hits: false, + size: 1, + _source: ['span.destination.service'], + query: { + bool: { + filter: [ + ...termQuery(TRACE_ID, traceId), + ...termQuery(EVENT_OUTCOME, 'failure'), + ...rangeQuery(start, end), + { exists: { field: SPAN_DESTINATION_SERVICE_RESOURCE } }, + ], }, - fields: requiredFields, }, + fields: requiredFields, }); const event = unflattenKnownApmEventFields(maybe(response.hits.hits[0])?.fields, requiredFields); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_service_name_from_signals.ts b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_service_name_from_signals.ts index 936c40c49fbc0..23b8013a6b32d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_service_name_from_signals.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/assistant_functions/get_observability_alert_details_context/get_service_name_from_signals.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import { rangeQuery, termQuery, typedSearch } from '@kbn/observability-plugin/server/utils/queries'; import type * as t from 'io-ts'; @@ -45,7 +45,7 @@ export async function getServiceNameFromSignals({ const start = moment(query.alert_started_at).subtract(30, 'minutes').valueOf(); const end = moment(query.alert_started_at).valueOf(); - const params: APMEventESSearchRequest['body'] = { + const params: Omit = { _source: ['service.name'], terminate_after: 1, size: 1, @@ -86,7 +86,7 @@ async function getServiceNameFromLogs({ esClient, logSourcesService, }: { - params: ESSearchRequest['body']; + params: ESSearchRequest; esClient: ElasticsearchClient; logSourcesService: LogSourcesService; }) { @@ -103,7 +103,7 @@ async function getServiceNameFromTraces({ params, apmEventClient, }: { - params: APMEventESSearchRequest['body']; + params: Omit; apmEventClient: APMEventClient; }) { const requiredFields = asMutableArray([SERVICE_NAME] as const); @@ -116,10 +116,8 @@ async function getServiceNameFromTraces({ }, ], }, - body: { - ...params, - fields: requiredFields, - }, + ...params, + fields: requiredFields, }); const event = unflattenKnownApmEventFields(maybe(res.hits.hits[0])?.fields, requiredFields); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation.ts index a6c76d882182c..7359d43af2bb3 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { SPAN_DURATION, TRANSACTION_DURATION } from '../../../../common/es_fields/apm'; import type { CommonCorrelationsQueryParams } from '../../../../common/correlations/types'; @@ -40,45 +40,43 @@ export const fetchDurationCorrelation = async ({ apm: { events: [eventType], }, - body: { - track_total_hits: false, - size: 0, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query, - }), - aggs: { - latency_ranges: { - range: { - field: eventType === ProcessorEvent.span ? SPAN_DURATION : TRANSACTION_DURATION, - ranges, - }, + track_total_hits: false, + size: 0, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query, + }), + aggs: { + latency_ranges: { + range: { + field: eventType === ProcessorEvent.span ? SPAN_DURATION : TRANSACTION_DURATION, + ranges, }, - // Pearson correlation value - duration_correlation: { - bucket_correlation: { - buckets_path: 'latency_ranges>_count', - function: { - count_correlation: { - indicator: { - fractions, - expectations, - doc_count: totalDocCount, - }, + }, + // Pearson correlation value + duration_correlation: { + bucket_correlation: { + buckets_path: 'latency_ranges>_count', + function: { + count_correlation: { + indicator: { + fractions, + expectations, + doc_count: totalDocCount, }, }, }, }, - // KS test p value = ks_test.less - ks_test: { - bucket_count_ks_test: { - fractions, - buckets_path: 'latency_ranges>_count', - alternative: ['less', 'greater', 'two_sided'], - }, + }, + // KS test p value = ks_test.less + ks_test: { + bucket_count_ks_test: { + fractions, + buckets_path: 'latency_ranges>_count', + alternative: ['less', 'greater', 'two_sided'], }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation_with_histogram.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation_with_histogram.ts index 7e26550d1f5e1..a7d1dfb8d9643 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation_with_histogram.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_correlation_with_histogram.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { termQuery } from '@kbn/observability-plugin/server'; import type { diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_field_candidates.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_field_candidates.ts index fcd7e445ff780..b5b2f85e603f4 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_field_candidates.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_field_candidates.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ES_FIELD_TYPES } from '@kbn/field-types'; import type { ProcessorEvent } from '@kbn/observability-plugin/common'; import { rangeQuery } from '@kbn/observability-plugin/server'; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_fractions.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_fractions.ts index 311f00e82e7ca..9ca04ad35145c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_fractions.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_fractions.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import type { CommonCorrelationsQueryParams } from '../../../../common/correlations/types'; @@ -34,22 +34,20 @@ export const fetchDurationFractions = async ({ apm: { events: [eventType], }, - body: { - track_total_hits: false, - size: 0, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query, - }), - aggs: { - latency_ranges: { - range: { - field: eventType === ProcessorEvent.span ? SPAN_DURATION : TRANSACTION_DURATION, - ranges, - }, + track_total_hits: false, + size: 0, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query, + }), + aggs: { + latency_ranges: { + range: { + field: eventType === ProcessorEvent.span ? SPAN_DURATION : TRANSACTION_DURATION, + ranges, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_histogram_range_steps.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_histogram_range_steps.ts index 0105ba4faaf37..f665dbc80617f 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_histogram_range_steps.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_histogram_range_steps.ts @@ -73,20 +73,18 @@ export const fetchDurationHistogramRangeSteps = async ({ apm: { events: [getEventType(chartType, searchMetrics)], }, - body: { - track_total_hits: 1, - size: 0, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query: filteredQuery, - }), - aggs: { - duration_min: { min: { field: durationField } }, - duration_max: { max: { field: durationField } }, - }, + track_total_hits: 1, + size: 0, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query: filteredQuery, + }), + aggs: { + duration_min: { min: { field: durationField } }, + duration_max: { max: { field: durationField } }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_percentiles.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_percentiles.ts index 92cd5abe541fe..e0d5cee324739 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_percentiles.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_percentiles.ts @@ -43,25 +43,23 @@ export const fetchDurationPercentiles = async ({ const params = { apm: { events: [getEventType(chartType, searchMetrics)] }, - body: { - track_total_hits: true, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query: filteredQuery, - }), - size: 0, - aggs: { - duration_percentiles: { - percentiles: { - hdr: { - number_of_significant_value_digits: SIGNIFICANT_VALUE_DIGITS, - }, - field: getDurationField(chartType, searchMetrics), - ...(Array.isArray(percents) ? { percents } : {}), + track_total_hits: true, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query: filteredQuery, + }), + size: 0, + aggs: { + duration_percentiles: { + percentiles: { + hdr: { + number_of_significant_value_digits: SIGNIFICANT_VALUE_DIGITS, }, + field: getDurationField(chartType, searchMetrics), + ...(Array.isArray(percents) ? { percents } : {}), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_ranges.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_ranges.ts index 1078235ce8ec3..7ef286c905dd1 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_ranges.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_duration_ranges.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { sumBy } from 'lodash'; import type { LatencyDistributionChartType } from '../../../../common/latency_distribution_chart_types'; import { getCommonCorrelationsQuery } from './get_common_correlations_query'; @@ -63,22 +63,20 @@ export const fetchDurationRanges = async ({ apm: { events: [getEventType(chartType, searchMetrics)], }, - body: { - track_total_hits: false, - size: 0, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query: filteredQuery, - }), - aggs: { - logspace_ranges: { - range: { - field: getDurationField(chartType, searchMetrics), - ranges, - }, + track_total_hits: false, + size: 0, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query: filteredQuery, + }), + aggs: { + logspace_ranges: { + range: { + field: getDurationField(chartType, searchMetrics), + ranges, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_failed_events_correlation_p_values.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_failed_events_correlation_p_values.ts index 7df5fc9e73c88..05ad80237db08 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_failed_events_correlation_p_values.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_failed_events_correlation_p_values.ts @@ -45,29 +45,27 @@ export const fetchFailedEventsCorrelationPValues = async ({ apm: { events: [eventType], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [commonQuery, ...termQuery(EVENT_OUTCOME, EventOutcome.failure)], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [commonQuery, ...termQuery(EVENT_OUTCOME, EventOutcome.failure)], }, - aggs: { - failure_p_value: { - significant_terms: { - field: fieldName, - background_filter: { - // Important to have same query as above here - // without it, we would be comparing sets of different filtered elements - bool: { - filter: [commonQuery, ...termQuery(PROCESSOR_EVENT, eventType)], - }, + }, + aggs: { + failure_p_value: { + significant_terms: { + field: fieldName, + background_filter: { + // Important to have same query as above here + // without it, we would be comparing sets of different filtered elements + bool: { + filter: [commonQuery, ...termQuery(PROCESSOR_EVENT, eventType)], }, - // No need to have must_not "event.outcome": "failure" clause - // if background_is_superset is set to true - p_value: { background_is_superset: true }, }, + // No need to have must_not "event.outcome": "failure" clause + // if background_is_superset is set to true + p_value: { background_is_superset: true }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_field_value_pairs.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_field_value_pairs.ts index ee0d9ec875626..5b574dbc9b6eb 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_field_value_pairs.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/fetch_field_value_pairs.ts @@ -42,22 +42,20 @@ export const fetchFieldValuePairs = async ({ apm: { events: [eventType], }, - body: { - track_total_hits: false, - size: 0, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query, - }), - aggs: { - attribute_terms: { - terms: { - field: fieldName, - size: TERMS_SIZE, - }, + track_total_hits: false, + size: 0, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query, + }), + aggs: { + attribute_terms: { + terms: { + field: fieldName, + size: TERMS_SIZE, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/field_stats/fetch_field_value_field_stats.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/field_stats/fetch_field_value_field_stats.ts index b848e9fcbd61c..24dbdc7fb379d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/field_stats/fetch_field_value_field_stats.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/field_stats/fetch_field_value_field_stats.ts @@ -10,7 +10,7 @@ import type { AggregationsAggregationContainer, AggregationsSamplerAggregate, AggregationsSingleBucketAggregateBase, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { CommonCorrelationsQueryParams, FieldValuePair, @@ -72,18 +72,16 @@ export const fetchFieldValueFieldStats = async ({ apm: { events: [eventType], }, - body: { - size: 0, - track_total_hits: false, - query: getCommonCorrelationsQuery({ - start, - end, - environment, - kuery, - query, - }), - aggs, - }, + size: 0, + track_total_hits: false, + query: getCommonCorrelationsQuery({ + start, + end, + environment, + kuery, + query, + }), + aggs, }); const results = ( diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/get_common_correlations_query.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/get_common_correlations_query.ts index e82870d6d4057..47957d2114756 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/get_common_correlations_query.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/queries/get_common_correlations_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { kqlQuery, rangeQuery } from '@kbn/observability-plugin/server'; import type { CommonCorrelationsQueryParams } from '../../../../common/correlations/types'; import { environmentQuery } from '../../../../common/utils/environment_query'; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.ts b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.ts index 19fb1e6370cc2..902d9fb123737 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { PERCENTILES_STEP } from '../../../../common/correlations/constants'; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts b/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts index 1f156ed297b9a..391eeabe689a0 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts @@ -13,14 +13,12 @@ import type { EntitiesESClient } from '../../lib/helpers/create_es_client/create function getSearchRequest(filters: estypes.QueryDslQueryContainer[]) { return { - body: { - track_total_hits: false, - terminate_after: 1, - size: 1, - query: { - bool: { - filter: filters, - }, + track_total_hits: false, + terminate_after: 1, + size: 1, + query: { + bool: { + filter: filters, }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_services_with_dashboards.ts b/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_services_with_dashboards.ts index 30b3e44cf9584..f27b210c41e67 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_services_with_dashboards.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/custom_dashboards/get_services_with_dashboards.ts @@ -20,14 +20,12 @@ function getSearchRequest(filters: estypes.QueryDslQueryContainer[]): APMEventES apm: { events: [ProcessorEvent.metric, ProcessorEvent.transaction], }, - body: { - track_total_hits: false, - terminate_after: 1, - size: 1, - query: { - bool: { - filter: filters, - }, + track_total_hits: false, + terminate_after: 1, + size: 1, + query: { + bool: { + filter: filters, }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_error_rate_charts_for_dependency.ts b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_error_rate_charts_for_dependency.ts index 2938e604fbf1a..a63640760991d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_error_rate_charts_for_dependency.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_error_rate_charts_for_dependency.ts @@ -55,66 +55,62 @@ async function getErrorRateChartsForDependencyForTimeRange({ apm: { events: [getProcessorEventForServiceDestinationStatistics(searchServiceDestinationMetrics)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(startWithOffset, endWithOffset), - ...termQuery(SPAN_NAME, spanName || null), - ...getDocumentTypeFilterForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - { term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName } }, - { - terms: { - [EVENT_OUTCOME]: [EventOutcome.success, EventOutcome.failure], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(startWithOffset, endWithOffset), + ...termQuery(SPAN_NAME, spanName || null), + ...getDocumentTypeFilterForServiceDestinationStatistics(searchServiceDestinationMetrics), + { term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName } }, + { + terms: { + [EVENT_OUTCOME]: [EventOutcome.success, EventOutcome.failure], }, - ], - }, + }, + ], }, - aggs: { - timeseries: { - date_histogram: getMetricsDateHistogramParams({ - start: startWithOffset, - end: endWithOffset, - metricsInterval: 60, - }), - aggs: { - ...(searchServiceDestinationMetrics - ? { - total_count: { - sum: { - field: getDocCountFieldForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - }, + }, + aggs: { + timeseries: { + date_histogram: getMetricsDateHistogramParams({ + start: startWithOffset, + end: endWithOffset, + metricsInterval: 60, + }), + aggs: { + ...(searchServiceDestinationMetrics + ? { + total_count: { + sum: { + field: getDocCountFieldForServiceDestinationStatistics( + searchServiceDestinationMetrics + ), }, - } - : {}), - failures: { - filter: { - term: { - [EVENT_OUTCOME]: EventOutcome.failure, }, + } + : {}), + failures: { + filter: { + term: { + [EVENT_OUTCOME]: EventOutcome.failure, }, - aggs: { - ...(searchServiceDestinationMetrics - ? { - total_count: { - sum: { - field: getDocCountFieldForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - }, + }, + aggs: { + ...(searchServiceDestinationMetrics + ? { + total_count: { + sum: { + field: getDocCountFieldForServiceDestinationStatistics( + searchServiceDestinationMetrics + ), }, - } - : {}), - }, + }, + } + : {}), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_latency_charts_for_dependency.ts b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_latency_charts_for_dependency.ts index 7aafa9729675d..b50c644c455b7 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_latency_charts_for_dependency.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_latency_charts_for_dependency.ts @@ -51,50 +51,46 @@ async function getLatencyChartsForDependencyForTimeRange({ apm: { events: [getProcessorEventForServiceDestinationStatistics(searchServiceDestinationMetrics)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(startWithOffset, endWithOffset), - ...termQuery(SPAN_NAME, spanName || null), - ...getDocumentTypeFilterForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - { term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName } }, - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(startWithOffset, endWithOffset), + ...termQuery(SPAN_NAME, spanName || null), + ...getDocumentTypeFilterForServiceDestinationStatistics(searchServiceDestinationMetrics), + { term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName } }, + ], }, - aggs: { - timeseries: { - date_histogram: getMetricsDateHistogramParams({ - start: startWithOffset, - end: endWithOffset, - metricsInterval: 60, - }), - aggs: { - latency_sum: { - sum: { - field: getLatencyFieldForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - }, + }, + aggs: { + timeseries: { + date_histogram: getMetricsDateHistogramParams({ + start: startWithOffset, + end: endWithOffset, + metricsInterval: 60, + }), + aggs: { + latency_sum: { + sum: { + field: getLatencyFieldForServiceDestinationStatistics( + searchServiceDestinationMetrics + ), }, - ...(searchServiceDestinationMetrics - ? { - latency_count: { - sum: { - field: getDocCountFieldForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - }, - }, - } - : {}), }, + ...(searchServiceDestinationMetrics + ? { + latency_count: { + sum: { + field: getDocCountFieldForServiceDestinationStatistics( + searchServiceDestinationMetrics + ), + }, + }, + } + : {}), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_metadata_for_dependency.ts b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_metadata_for_dependency.ts index aaf12cb0b2fea..960f65e41e789 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_metadata_for_dependency.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_metadata_for_dependency.ts @@ -38,26 +38,24 @@ export async function getMetadataForDependency({ apm: { events: [ProcessorEvent.span], }, - body: { - track_total_hits: false, - size: 1, - query: { - bool: { - filter: [ - { - term: { - [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName, - }, + track_total_hits: false, + size: 1, + query: { + bool: { + filter: [ + { + term: { + [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName, }, - ...rangeQuery(start, end), - ], - }, - }, - fields, - sort: { - '@timestamp': 'desc', + }, + ...rangeQuery(start, end), + ], }, }, + fields, + sort: { + '@timestamp': 'desc', + }, }); const sample = unflattenKnownApmEventFields(maybe(sampleResponse.hits.hits[0])?.fields); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_throughput_charts_for_dependency.ts b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_throughput_charts_for_dependency.ts index dc763a33ab31a..10428e9d73b43 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_throughput_charts_for_dependency.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_throughput_charts_for_dependency.ts @@ -61,43 +61,39 @@ async function getThroughputChartsForDependencyForTimeRange({ apm: { events: [getProcessorEventForServiceDestinationStatistics(searchServiceDestinationMetrics)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(startWithOffset, endWithOffset), - ...termQuery(SPAN_NAME, spanName || null), - ...getDocumentTypeFilterForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - { term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName } }, - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(startWithOffset, endWithOffset), + ...termQuery(SPAN_NAME, spanName || null), + ...getDocumentTypeFilterForServiceDestinationStatistics(searchServiceDestinationMetrics), + { term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName } }, + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs: { - throughput: { - rate: { - ...(searchServiceDestinationMetrics - ? { - field: getDocCountFieldForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - } - : {}), - unit: 'minute', - }, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, + }, + aggs: { + throughput: { + rate: { + ...(searchServiceDestinationMetrics + ? { + field: getDocCountFieldForServiceDestinationStatistics( + searchServiceDestinationMetrics + ), + } + : {}), + unit: 'minute', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_operations.ts b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_operations.ts index c03c8ed2ce2a0..2004448735e24 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_operations.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_operations.ts @@ -106,45 +106,41 @@ export async function getTopDependencyOperations({ apm: { events: [getProcessorEventForServiceDestinationStatistics(searchServiceDestinationMetrics)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(SPAN_DESTINATION_SERVICE_RESOURCE, dependencyName), - ...getDocumentTypeFilterForServiceDestinationStatistics( - searchServiceDestinationMetrics - ), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(SPAN_DESTINATION_SERVICE_RESOURCE, dependencyName), + ...getDocumentTypeFilterForServiceDestinationStatistics(searchServiceDestinationMetrics), + ], }, - aggs: { - operationName: { - terms: { - field: SPAN_NAME, - size: MAX_NUM_OPERATIONS, - }, - aggs: { - over_time: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, - }, + }, + aggs: { + operationName: { + terms: { + field: SPAN_NAME, + size: MAX_NUM_OPERATIONS, + }, + aggs: { + over_time: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, - aggs, - }, - ...aggs, - total_time: { - sum: { field }, }, + aggs, + }, + ...aggs, + total_time: { + sum: { field }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_spans.ts b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_spans.ts index 142bdfb0076bc..0f0c7c526b8e9 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_spans.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/dependencies/get_top_dependency_spans.ts @@ -86,34 +86,32 @@ export async function getTopDependencySpans({ apm: { events: [ProcessorEvent.span], }, - body: { - track_total_hits: false, - size: MAX_NUM_SPANS, - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(SPAN_DESTINATION_SERVICE_RESOURCE, dependencyName), - ...termQuery(SPAN_NAME, spanName), - ...((sampleRangeFrom ?? 0) >= 0 && (sampleRangeTo ?? 0) > 0 - ? [ - { - range: { - [SPAN_DURATION]: { - gte: sampleRangeFrom, - lte: sampleRangeTo, - }, + track_total_hits: false, + size: MAX_NUM_SPANS, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(SPAN_DESTINATION_SERVICE_RESOURCE, dependencyName), + ...termQuery(SPAN_NAME, spanName), + ...((sampleRangeFrom ?? 0) >= 0 && (sampleRangeTo ?? 0) > 0 + ? [ + { + range: { + [SPAN_DURATION]: { + gte: sampleRangeFrom, + lte: sampleRangeTo, }, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, - fields: topDedsRequiredFields, }, + fields: topDedsRequiredFields, }) ).hits.hits.map((hit) => unflattenKnownApmEventFields(hit.fields, topDedsRequiredFields)); @@ -131,19 +129,17 @@ export async function getTopDependencySpans({ apm: { events: [ProcessorEvent.transaction], }, - body: { - track_total_hits: false, - size: traceIds.length, - query: { - bool: { - filter: [...termsQuery(TRACE_ID, ...traceIds), { exists: { field: TRANSACTION_ID } }], - }, - }, - fields: txRequiredFields, - sort: { - '@timestamp': 'desc', + track_total_hits: false, + size: traceIds.length, + query: { + bool: { + filter: [...termsQuery(TRACE_ID, ...traceIds), { exists: { field: TRANSACTION_ID } }], }, }, + fields: txRequiredFields, + sort: { + '@timestamp': 'desc', + }, }) ).hits.hits.map((hit) => unflattenKnownApmEventFields(hit.fields, txRequiredFields)); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/diagnostics/helpers/get_diagnostic_privileges.ts b/x-pack/solutions/observability/plugins/apm/server/routes/diagnostics/helpers/get_diagnostic_privileges.ts index 18d98bddd0f7a..9924a5dee184a 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/diagnostics/helpers/get_diagnostic_privileges.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/diagnostics/helpers/get_diagnostic_privileges.ts @@ -25,15 +25,13 @@ export async function getDiagnosticsPrivileges({ const clusterPrivileges = ['manage_index_templates', 'monitor', 'read_pipeline']; const { index, cluster } = await esClient.security.hasPrivileges({ - body: { - index: [ - { - names: indexPatterns, - privileges: ['read'], - }, - ], - cluster: clusterPrivileges, - }, + index: [ + { + names: indexPatterns, + privileges: ['read'], + }, + ], + cluster: clusterPrivileges, }); const hasAllIndexPrivileges = Object.values(index).every((indexPrivs) => diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/environments/__snapshots__/get_all_environments.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/environments/__snapshots__/get_all_environments.test.ts.snap index 9842d716001f8..4996a084a542d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/environments/__snapshots__/get_all_environments.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/environments/__snapshots__/get_all_environments.test.ts.snap @@ -2,6 +2,15 @@ exports[`getAllEnvironments fetches all environments 1`] = ` Object { + "aggs": Object { + "environments": Object { + "terms": Object { + "field": "service.environment", + "missing": undefined, + "size": 50, + }, + }, + }, "apm": Object { "events": Array [ "transaction", @@ -9,35 +18,33 @@ Object { "metric", ], }, - "body": Object { - "aggs": Object { - "environments": Object { - "terms": Object { - "field": "service.environment", - "missing": undefined, - "size": 50, - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "test", - }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "test", }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; exports[`getAllEnvironments fetches all environments with includeMissing 1`] = ` Object { + "aggs": Object { + "environments": Object { + "terms": Object { + "field": "service.environment", + "missing": "ENVIRONMENT_NOT_DEFINED", + "size": 50, + }, + }, + }, "apm": Object { "events": Array [ "transaction", @@ -45,29 +52,18 @@ Object { "metric", ], }, - "body": Object { - "aggs": Object { - "environments": Object { - "terms": Object { - "field": "service.environment", - "missing": "ENVIRONMENT_NOT_DEFINED", - "size": 50, - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "test", - }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "test", }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_all_environments.ts b/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_all_environments.ts index acbbb76f1c2cb..a9d7c7cfa7483 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_all_environments.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_all_environments.ts @@ -41,25 +41,23 @@ export async function getAllEnvironments({ ProcessorEvent.metric, ], }, - body: { - // use timeout + min_doc_count to return as early as possible - // if filter is not defined to prevent timeouts - ...(!serviceName ? { timeout: '1ms' } : {}), - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...termQuery(SERVICE_NAME, serviceName)], - }, + // use timeout + min_doc_count to return as early as possible + // if filter is not defined to prevent timeouts + ...(!serviceName ? { timeout: '1ms' } : {}), + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...termQuery(SERVICE_NAME, serviceName)], }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - size, - ...(!serviceName ? { min_doc_count: 0 } : {}), - missing: includeMissing ? ENVIRONMENT_NOT_DEFINED.value : undefined, - }, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, + size, + ...(!serviceName ? { min_doc_count: 0 } : {}), + missing: includeMissing ? ENVIRONMENT_NOT_DEFINED.value : undefined, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_environments.ts b/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_environments.ts index 1eeb03087396a..816be5a8652f1 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_environments.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/environments/get_environments.ts @@ -42,21 +42,19 @@ export async function getEnvironments({ ProcessorEvent.error, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...rangeQuery(start, end), ...termQuery(SERVICE_NAME, serviceName)], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...rangeQuery(start, end), ...termQuery(SERVICE_NAME, serviceName)], }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - missing: ENVIRONMENT_NOT_DEFINED.value, - size, - }, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, + missing: ENVIRONMENT_NOT_DEFINED.value, + size, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/get_buckets.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/get_buckets.test.ts.snap index 7d8d396a01de0..5890250ee7826 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/get_buckets.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/get_buckets.test.ts.snap @@ -5,6 +5,19 @@ Array [ Array [ "get_error_distribution_buckets", Object { + "aggs": Object { + "distribution": Object { + "histogram": Object { + "extended_bounds": Object { + "max": 1528977600000, + "min": 1528113600000, + }, + "field": "@timestamp", + "interval": 10, + "min_doc_count": 0, + }, + }, + }, "apm": Object { "sources": Array [ Object { @@ -13,53 +26,38 @@ Array [ }, ], }, - "body": Object { - "aggs": Object { - "distribution": Object { - "histogram": Object { - "extended_bounds": Object { - "max": 1528977600000, - "min": 1528113600000, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "myServiceName", }, - "field": "@timestamp", - "interval": 10, - "min_doc_count": 0, }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "myServiceName", + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, }, }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 1528113600000, - "lte": 1528977600000, - }, - }, - }, - Object { - "term": Object { - "service.environment": "prod", - }, - }, - ], - "must_not": Object { + }, + Object { "term": Object { - "error.type": "crash", + "service.environment": "prod", }, }, + ], + "must_not": Object { + "term": Object { + "error.type": "crash", + }, }, }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, }, ], ] diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/queries.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/queries.test.ts.snap index 3ef42dc70bcee..8b88703a529f9 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/queries.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/__snapshots__/queries.test.ts.snap @@ -2,6 +2,19 @@ exports[`error distribution queries fetches an error distribution 1`] = ` Object { + "aggs": Object { + "distribution": Object { + "histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "interval": 3333, + "min_doc_count": 0, + }, + }, + }, "apm": Object { "sources": Array [ Object { @@ -10,53 +23,51 @@ Object { }, ], }, - "body": Object { - "aggs": Object { - "distribution": Object { - "histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "serviceName", }, - "field": "@timestamp", - "interval": 3333, - "min_doc_count": 0, }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "serviceName", + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, - }, - }, - ], - "must_not": Object { - "term": Object { - "error.type": "crash", - }, + }, + ], + "must_not": Object { + "term": Object { + "error.type": "crash", }, }, }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; exports[`error distribution queries fetches an error distribution with a group id 1`] = ` Object { + "aggs": Object { + "distribution": Object { + "histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "interval": 3333, + "min_doc_count": 0, + }, + }, + }, "apm": Object { "sources": Array [ Object { @@ -65,52 +76,37 @@ Object { }, ], }, - "body": Object { - "aggs": Object { - "distribution": Object { - "histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "serviceName", }, - "field": "@timestamp", - "interval": 3333, - "min_doc_count": 0, }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "serviceName", + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, - }, - }, - Object { - "term": Object { - "error.grouping_key": "foo", - }, - }, - ], - "must_not": Object { + }, + Object { "term": Object { - "error.type": "crash", + "error.grouping_key": "foo", }, }, + ], + "must_not": Object { + "term": Object { + "error.type": "crash", + }, }, }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/get_buckets.ts b/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/get_buckets.ts index 58a0b97ee25d6..3f45fbb9b1026 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/get_buckets.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/distribution/get_buckets.ts @@ -40,33 +40,31 @@ export async function getBuckets({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - must_not: { - term: { 'error.type': 'crash' }, - }, - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(ERROR_GROUP_ID, groupId), - ], + track_total_hits: false, + size: 0, + query: { + bool: { + must_not: { + term: { 'error.type': 'crash' }, }, + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(ERROR_GROUP_ID, groupId), + ], }, - aggs: { - distribution: { - histogram: { - field: '@timestamp', - min_doc_count: 0, - interval: bucketSize, - extended_bounds: { - min: start, - max: end, - }, + }, + aggs: { + distribution: { + histogram: { + field: '@timestamp', + min_doc_count: 0, + interval: bucketSize, + extended_bounds: { + min: start, + max: end, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/erroneous_transactions/get_top_erroneous_transactions.ts b/x-pack/solutions/observability/plugins/apm/server/routes/errors/erroneous_transactions/get_top_erroneous_transactions.ts index dd542cc6a9126..5f373241aacbc 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/erroneous_transactions/get_top_erroneous_transactions.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/erroneous_transactions/get_top_erroneous_transactions.ts @@ -69,41 +69,39 @@ async function getTopErroneousTransactions({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(ERROR_GROUP_ID, groupId), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(ERROR_GROUP_ID, groupId), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - top_five_transactions: { - terms: { - field: TRANSACTION_NAME, - size: 5, - }, - aggs: { - sample: { - top_hits: { - size: 1, - _source: [TRANSACTION_TYPE], - }, + }, + aggs: { + top_five_transactions: { + terms: { + field: TRANSACTION_NAME, + size: 5, + }, + aggs: { + sample: { + top_hits: { + size: 1, + _source: [TRANSACTION_TYPE], }, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, - }, + }, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_detailed_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_detailed_statistics.ts index be48580a7ddec..9c8bf61308cfd 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_detailed_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_detailed_statistics.ts @@ -59,36 +59,34 @@ export async function getErrorGroupDetailedStatistics({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termsQuery(ERROR_GROUP_ID, ...groupIds), - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termsQuery(ERROR_GROUP_ID, ...groupIds), + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - error_groups: { - terms: { - field: ERROR_GROUP_ID, - size: 500, - }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, - }, + }, + aggs: { + error_groups: { + terms: { + field: ERROR_GROUP_ID, + size: 500, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_main_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_main_statistics.ts index 925da8a33cc9d..2d0ed0b2e6e14 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_main_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_main_statistics.ts @@ -116,44 +116,42 @@ export async function getErrorGroupMainStatistics({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(TRANSACTION_NAME, transactionName), - ...termQuery(TRANSACTION_TYPE, transactionType), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...shouldMatchSearchQuery, - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(TRANSACTION_NAME, transactionName), + ...termQuery(TRANSACTION_TYPE, transactionType), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...shouldMatchSearchQuery, + ], }, - aggs: { - error_groups: { - terms: { - field: ERROR_GROUP_ID, - size: maxNumberOfErrorGroups, - order, - }, - aggs: { - sample: { - top_hits: { - size: 1, - fields: [...requiredFields, ...optionalFields], - _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], - sort: { - '@timestamp': 'desc', - }, + }, + aggs: { + error_groups: { + terms: { + field: ERROR_GROUP_ID, + size: maxNumberOfErrorGroups, + order, + }, + aggs: { + sample: { + top_hits: { + size: 1, + fields: [...requiredFields, ...optionalFields], + _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], + sort: { + '@timestamp': 'desc', }, }, - ...(sortByLatestOccurrence - ? { [maxTimestampAggKey]: { max: { field: '@timestamp' } } } - : {}), }, + ...(sortByLatestOccurrence + ? { [maxTimestampAggKey]: { max: { field: '@timestamp' } } } + : {}), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_sample_ids.ts b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_sample_ids.ts index 508e2353e7777..706c9c228d2c8 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_sample_ids.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_group_sample_ids.ts @@ -53,27 +53,25 @@ export async function getErrorGroupSampleIds({ }, ], }, - body: { - track_total_hits: ERROR_SAMPLES_SIZE, - size: ERROR_SAMPLES_SIZE, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - { term: { [ERROR_GROUP_ID]: groupId } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - should: [{ term: { [TRANSACTION_SAMPLED]: true } }], // prefer error samples with related transactions - }, + track_total_hits: ERROR_SAMPLES_SIZE, + size: ERROR_SAMPLES_SIZE, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + { term: { [ERROR_GROUP_ID]: groupId } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], + should: [{ term: { [TRANSACTION_SAMPLED]: true } }], // prefer error samples with related transactions }, - fields: requiredFields, - sort: asMutableArray([ - { _score: { order: 'desc' } }, // sort by _score first to ensure that errors with transaction.sampled:true ends up on top - { '@timestamp': { order: 'desc' } }, // sort by timestamp to get the most recent error - ] as const), }, + fields: requiredFields, + sort: asMutableArray([ + { _score: { order: 'desc' } }, // sort by _score first to ensure that errors with transaction.sampled:true ends up on top + { '@timestamp': { order: 'desc' } }, // sort by timestamp to get the most recent error + ] as const), }); const errorSampleIds = resp.hits.hits.map((item) => { const event = unflattenKnownApmEventFields(item.fields, requiredFields); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_sample_details.ts b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_sample_details.ts index c16896f2a80c1..f36f056171f0c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_sample_details.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/errors/get_error_groups/get_error_sample_details.ts @@ -101,23 +101,21 @@ export async function getErrorSampleDetails({ }, ], }, - body: { - track_total_hits: false, - size: 1, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - { term: { [ERROR_ID]: errorId } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 1, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + { term: { [ERROR_ID]: errorId } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - fields: [...requiredFields, ...optionalFields], - _source: [ERROR_EXCEPTION, 'error.log'], }, + fields: [...requiredFields, ...optionalFields], + _source: [ERROR_EXCEPTION, 'error.log'], }; const resp = await apmEventClient.search('get_error_sample_details', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/event_metadata/get_event_metadata.ts b/x-pack/solutions/observability/plugins/apm/server/routes/event_metadata/get_event_metadata.ts index da5f2c61f0506..dc1b8f8d5b904 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/event_metadata/get_event_metadata.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/event_metadata/get_event_metadata.ts @@ -28,17 +28,15 @@ export async function getEventMetadata({ apm: { events: [processorEvent], }, - body: { - track_total_hits: false, - query: { - bool: { - filter: [...rangeQuery(start, end), { term: { [fieldName]: id } }], - }, + track_total_hits: false, + query: { + bool: { + filter: [...rangeQuery(start, end), { term: { [fieldName]: id } }], }, - size: 1, - _source: false, - fields: [{ field: '*', include_unmapped: true }], }, + size: 1, + _source: false, + fields: [{ field: '*', include_unmapped: true }], terminate_after: 1, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/fleet/api_keys/create_apm_api_keys.ts b/x-pack/solutions/observability/plugins/apm/server/routes/fleet/api_keys/create_apm_api_keys.ts index 7b64a477d7b2e..6155c2d279372 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/fleet/api_keys/create_apm_api_keys.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/fleet/api_keys/create_apm_api_keys.ts @@ -31,24 +31,22 @@ export async function createApmSourceMapApiKey({ logger.debug('Creating source map API Key'); const response = await coreStart.elasticsearch.client.asInternalUser.security.createApiKey({ - body: { - name: `Source map read access (Package policy: "${packagePolicyId}")`, - metadata: { - ...apiKeyMetadata, - description: 'Provides read access to the source maps index. Created for APM Server', - package_policy_id: packagePolicyId, - type: 'source-map', - }, - role_descriptors: { - apmSystemIndices: { - index: [ - { - names: [APM_SOURCE_MAP_INDEX], - privileges: indexLevelPrivileges, - allow_restricted_indices: true, - }, - ], - }, + name: `Source map read access (Package policy: "${packagePolicyId}")`, + metadata: { + ...apiKeyMetadata, + description: 'Provides read access to the source maps index. Created for APM Server', + package_policy_id: packagePolicyId, + type: 'source-map', + }, + role_descriptors: { + apmSystemIndices: { + index: [ + { + names: [APM_SOURCE_MAP_INDEX], + privileges: indexLevelPrivileges, + allow_restricted_indices: true, + }, + ], }, }, }); @@ -70,25 +68,22 @@ export async function createApmAgentConfigApiKey({ logger.debug('Creating agent configuration API Key'); const response = await coreStart.elasticsearch.client.asInternalUser.security.createApiKey({ - body: { - name: `Agent Configuration read access (Package policy: "${packagePolicyId}")`, - metadata: { - ...apiKeyMetadata, - description: - 'Provides read access to the agent configurations index. Created for APM Server', - package_policy_id: packagePolicyId, - type: 'agent-configuration', - }, - role_descriptors: { - apmSystemIndices: { - index: [ - { - names: [APM_AGENT_CONFIGURATION_INDEX], - privileges: indexLevelPrivileges, - allow_restricted_indices: true, - }, - ], - }, + name: `Agent Configuration read access (Package policy: "${packagePolicyId}")`, + metadata: { + ...apiKeyMetadata, + description: 'Provides read access to the agent configurations index. Created for APM Server', + package_policy_id: packagePolicyId, + type: 'agent-configuration', + }, + role_descriptors: { + apmSystemIndices: { + index: [ + { + names: [APM_AGENT_CONFIGURATION_INDEX], + privileges: indexLevelPrivileges, + allow_restricted_indices: true, + }, + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts b/x-pack/solutions/observability/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts index 4a32ab0178e03..2a2f197dfde24 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts @@ -100,7 +100,8 @@ function onPackagePolicyDelete({ try { await internalESClient.security.invalidateApiKey({ - body: { ids: [agentConfigApiKeyId, sourceMapApiKeyId], owner: true }, + ids: [agentConfigApiKeyId, sourceMapApiKeyId], + owner: true, }); } catch (e) { logger.error( diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts b/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts index ab7fe11a38c8b..77adf2ee1e8cd 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts @@ -33,12 +33,10 @@ async function hasDataRequest(apmEventClient: APMEventClient, dataTiers?: DataTi apm: { events: [ProcessorEvent.error, ProcessorEvent.metric, ProcessorEvent.transaction], }, - body: { - terminate_after: 1, - track_total_hits: 1, - size: 0, - query, - }, + terminate_after: 1, + track_total_hits: 1, + size: 0, + query, }; const resp = await apmEventClient.search('has_historical_agent_data', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_entities_data.ts b/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_entities_data.ts index 747dc930ed1ed..db0423d4b78d7 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_entities_data.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/historical_data/has_historical_entities_data.ts @@ -11,11 +11,9 @@ import type { EntitiesESClient } from '../../lib/helpers/create_es_client/create export async function hasEntitiesData(entitiesESClient: EntitiesESClient, logger: Logger) { const params = { - body: { - terminate_after: 1, - track_total_hits: true, - size: 0, - }, + terminate_after: 1, + track_total_hits: true, + size: 0, }; try { diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/infrastructure/get_infrastructure_data.ts b/x-pack/solutions/observability/plugins/apm/server/routes/infrastructure/get_infrastructure_data.ts index 14dabb21098c6..39ad02c49d7c7 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/infrastructure/get_infrastructure_data.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/infrastructure/get_infrastructure_data.ts @@ -35,37 +35,35 @@ export const getInfrastructureData = async ({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - containerIds: { - terms: { - field: CONTAINER_ID, - size: 500, - }, + }, + aggs: { + containerIds: { + terms: { + field: CONTAINER_ID, + size: 500, }, - hostNames: { - terms: { - field: HOST_HOSTNAME, - size: 500, - }, + }, + hostNames: { + terms: { + field: HOST_HOSTNAME, + size: 500, }, - podNames: { - terms: { - field: KUBERNETES_POD_NAME, - size: 500, - }, + }, + podNames: { + terms: { + field: KUBERNETES_POD_NAME, + size: 500, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/get_overall_latency_distribution.ts b/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/get_overall_latency_distribution.ts index fa59e5bc81651..b2dc3bb736827 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/get_overall_latency_distribution.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/get_overall_latency_distribution.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Environment } from '../../../common/environment_rt'; import { withApmSpan } from '../../utils/with_apm_span'; import { fetchDurationRanges } from '../correlations/queries/fetch_duration_ranges'; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/route.ts b/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/route.ts index 413a80ae40bd9..4129ef72c699f 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/route.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/latency_distribution/route.ts @@ -8,7 +8,7 @@ import * as t from 'io-ts'; import { toNumberRt } from '@kbn/io-ts-utils'; import { termQuery } from '@kbn/observability-plugin/server'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { getOverallLatencyDistribution } from './get_overall_latency_distribution'; import { getSearchTransactionsEvents } from '../../lib/helpers/transactions'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/__snapshots__/queries.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/__snapshots__/queries.test.ts.snap index 18dd1f4c9835a..8185ddadbb980 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/__snapshots__/queries.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/__snapshots__/queries.test.ts.snap @@ -2,205 +2,195 @@ exports[`metrics queries with a service node name fetches cpu chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "processCPUAverage": Object { - "avg": Object { - "field": "system.process.cpu.total.norm.pct", - }, + "aggs": Object { + "processCPUAverage": Object { + "avg": Object { + "field": "system.process.cpu.total.norm.pct", }, - "processCPUMax": Object { - "max": Object { - "field": "system.process.cpu.total.norm.pct", - }, + }, + "processCPUMax": Object { + "max": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUAverage": Object { - "avg": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUAverage": Object { + "avg": Object { + "field": "system.cpu.total.norm.pct", }, - "systemCPUMax": Object { - "max": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUMax": Object { + "max": Object { + "field": "system.cpu.total.norm.pct", }, - "timeseriesData": Object { - "aggs": Object { - "processCPUAverage": Object { - "avg": Object { - "field": "system.process.cpu.total.norm.pct", - }, - }, - "processCPUMax": Object { - "max": Object { - "field": "system.process.cpu.total.norm.pct", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "processCPUAverage": Object { + "avg": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUAverage": Object { - "avg": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "processCPUMax": Object { + "max": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUMax": Object { - "max": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUAverage": Object { + "avg": Object { + "field": "system.cpu.total.norm.pct", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "systemCPUMax": Object { + "max": Object { + "field": "system.cpu.total.norm.pct", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "service.node.name": "bar", - }, + }, + Object { + "term": Object { + "service.node.name": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with a service node name fetches heap memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "heapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.heap.committed", - }, + "aggs": Object { + "heapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.heap.committed", }, - "heapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.heap.max", - }, + }, + "heapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.heap.max", }, - "heapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.heap.used", - }, + }, + "heapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.heap.used", }, - "timeseriesData": Object { - "aggs": Object { - "heapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.heap.committed", - }, - }, - "heapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.heap.max", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "heapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.heap.committed", }, - "heapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.heap.used", - }, + }, + "heapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.heap.max", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "heapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.heap.used", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "service.node.name": "bar", - }, + }, + Object { + "term": Object { + "service.node.name": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with a service node name fetches memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "memoryUsedAvg": Object { - "avg": Object { - "script": Object { - "lang": "painless", - "source": " + "aggs": Object { + "memoryUsedAvg": Object { + "avg": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -217,14 +207,14 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "memoryUsedMax": Object { - "max": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "memoryUsedMax": Object { + "max": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -241,16 +231,16 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "timeseriesData": Object { - "aggs": Object { - "memoryUsedAvg": Object { - "avg": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "timeseriesData": Object { + "aggs": Object { + "memoryUsedAvg": Object { + "avg": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -267,14 +257,14 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "memoryUsedMax": Object { - "max": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "memoryUsedMax": Object { + "max": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -291,465 +281,455 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, - }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, + }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "service.node.name": "bar", - }, + }, + Object { + "term": Object { + "service.node.name": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "system.process.cgroup.memory.mem.usage.bytes", - }, + }, + Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "system.process.cgroup.memory.mem.usage.bytes", }, - ], - "minimum_should_match": 1, - "should": Array [ - Object { - "exists": Object { - "field": "system.process.cgroup.memory.mem.limit.bytes", - }, + }, + ], + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "system.process.cgroup.memory.mem.limit.bytes", }, - Object { - "exists": Object { - "field": "system.memory.total", - }, + }, + Object { + "exists": Object { + "field": "system.memory.total", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with a service node name fetches non heap memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "nonHeapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.non_heap.committed", - }, + "aggs": Object { + "nonHeapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.non_heap.committed", }, - "nonHeapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.non_heap.max", - }, + }, + "nonHeapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.non_heap.max", }, - "nonHeapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.non_heap.used", - }, + }, + "nonHeapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.non_heap.used", }, - "timeseriesData": Object { - "aggs": Object { - "nonHeapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.non_heap.committed", - }, - }, - "nonHeapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.non_heap.max", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "nonHeapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.non_heap.committed", }, - "nonHeapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.non_heap.used", - }, + }, + "nonHeapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.non_heap.max", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "nonHeapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.non_heap.used", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "service.node.name": "bar", - }, + }, + Object { + "term": Object { + "service.node.name": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with a service node name fetches thread count chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "threadCount": Object { - "avg": Object { - "field": "jvm.thread.count", - }, + "aggs": Object { + "threadCount": Object { + "avg": Object { + "field": "jvm.thread.count", }, - "threadCountMax": Object { - "max": Object { - "field": "jvm.thread.count", - }, + }, + "threadCountMax": Object { + "max": Object { + "field": "jvm.thread.count", }, - "timeseriesData": Object { - "aggs": Object { - "threadCount": Object { - "avg": Object { - "field": "jvm.thread.count", - }, - }, - "threadCountMax": Object { - "max": Object { - "field": "jvm.thread.count", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "threadCount": Object { + "avg": Object { + "field": "jvm.thread.count", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "threadCountMax": Object { + "max": Object { + "field": "jvm.thread.count", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "service.node.name": "bar", - }, + }, + Object { + "term": Object { + "service.node.name": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with service_node_name_missing fetches cpu chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "processCPUAverage": Object { - "avg": Object { - "field": "system.process.cpu.total.norm.pct", - }, + "aggs": Object { + "processCPUAverage": Object { + "avg": Object { + "field": "system.process.cpu.total.norm.pct", }, - "processCPUMax": Object { - "max": Object { - "field": "system.process.cpu.total.norm.pct", - }, + }, + "processCPUMax": Object { + "max": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUAverage": Object { - "avg": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUAverage": Object { + "avg": Object { + "field": "system.cpu.total.norm.pct", }, - "systemCPUMax": Object { - "max": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUMax": Object { + "max": Object { + "field": "system.cpu.total.norm.pct", }, - "timeseriesData": Object { - "aggs": Object { - "processCPUAverage": Object { - "avg": Object { - "field": "system.process.cpu.total.norm.pct", - }, - }, - "processCPUMax": Object { - "max": Object { - "field": "system.process.cpu.total.norm.pct", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "processCPUAverage": Object { + "avg": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUAverage": Object { - "avg": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "processCPUMax": Object { + "max": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUMax": Object { - "max": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUAverage": Object { + "avg": Object { + "field": "system.cpu.total.norm.pct", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "systemCPUMax": Object { + "max": Object { + "field": "system.cpu.total.norm.pct", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, - }, - Object { - "bool": Object { - "must_not": Array [ - Object { - "exists": Object { - "field": "service.node.name", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "bool": Object { + "must_not": Array [ + Object { + "exists": Object { + "field": "service.node.name", }, - ], - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, }, + ], + }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with service_node_name_missing fetches heap memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "heapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.heap.committed", - }, + "aggs": Object { + "heapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.heap.committed", }, - "heapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.heap.max", - }, + }, + "heapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.heap.max", }, - "heapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.heap.used", - }, + }, + "heapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.heap.used", }, - "timeseriesData": Object { - "aggs": Object { - "heapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.heap.committed", - }, - }, - "heapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.heap.max", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "heapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.heap.committed", }, - "heapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.heap.used", - }, + }, + "heapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.heap.max", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "heapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.heap.used", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, - }, - Object { - "bool": Object { - "must_not": Array [ - Object { - "exists": Object { - "field": "service.node.name", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "bool": Object { + "must_not": Array [ + Object { + "exists": Object { + "field": "service.node.name", }, - ], - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, }, - }, + ], }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], + }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with service_node_name_missing fetches memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "memoryUsedAvg": Object { - "avg": Object { - "script": Object { - "lang": "painless", - "source": " + "aggs": Object { + "memoryUsedAvg": Object { + "avg": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -766,14 +746,14 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "memoryUsedMax": Object { - "max": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "memoryUsedMax": Object { + "max": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -790,16 +770,16 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "timeseriesData": Object { - "aggs": Object { - "memoryUsedAvg": Object { - "avg": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "timeseriesData": Object { + "aggs": Object { + "memoryUsedAvg": Object { + "avg": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -816,14 +796,14 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "memoryUsedMax": Object { - "max": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "memoryUsedMax": Object { + "max": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -840,461 +820,451 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, - }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, + }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, - }, - Object { - "bool": Object { - "must_not": Array [ - Object { - "exists": Object { - "field": "service.node.name", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "bool": Object { + "must_not": Array [ + Object { + "exists": Object { + "field": "service.node.name", }, - ], - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, }, + ], + }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "system.process.cgroup.memory.mem.usage.bytes", - }, + }, + Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "system.process.cgroup.memory.mem.usage.bytes", }, - ], - "minimum_should_match": 1, - "should": Array [ - Object { - "exists": Object { - "field": "system.process.cgroup.memory.mem.limit.bytes", - }, + }, + ], + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "system.process.cgroup.memory.mem.limit.bytes", }, - Object { - "exists": Object { - "field": "system.memory.total", - }, + }, + Object { + "exists": Object { + "field": "system.memory.total", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with service_node_name_missing fetches non heap memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "nonHeapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.non_heap.committed", - }, + "aggs": Object { + "nonHeapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.non_heap.committed", }, - "nonHeapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.non_heap.max", - }, + }, + "nonHeapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.non_heap.max", }, - "nonHeapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.non_heap.used", - }, + }, + "nonHeapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.non_heap.used", }, - "timeseriesData": Object { - "aggs": Object { - "nonHeapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.non_heap.committed", - }, - }, - "nonHeapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.non_heap.max", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "nonHeapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.non_heap.committed", }, - "nonHeapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.non_heap.used", - }, + }, + "nonHeapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.non_heap.max", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "nonHeapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.non_heap.used", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, - }, - Object { - "bool": Object { - "must_not": Array [ - Object { - "exists": Object { - "field": "service.node.name", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "bool": Object { + "must_not": Array [ + Object { + "exists": Object { + "field": "service.node.name", }, - ], - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, }, - }, + ], }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], + }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries with service_node_name_missing fetches thread count chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "threadCount": Object { - "avg": Object { - "field": "jvm.thread.count", - }, + "aggs": Object { + "threadCount": Object { + "avg": Object { + "field": "jvm.thread.count", }, - "threadCountMax": Object { - "max": Object { - "field": "jvm.thread.count", - }, + }, + "threadCountMax": Object { + "max": Object { + "field": "jvm.thread.count", }, - "timeseriesData": Object { - "aggs": Object { - "threadCount": Object { - "avg": Object { - "field": "jvm.thread.count", - }, - }, - "threadCountMax": Object { - "max": Object { - "field": "jvm.thread.count", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "threadCount": Object { + "avg": Object { + "field": "jvm.thread.count", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "threadCountMax": Object { + "max": Object { + "field": "jvm.thread.count", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, - }, - Object { - "bool": Object { - "must_not": Array [ - Object { - "exists": Object { - "field": "service.node.name", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "bool": Object { + "must_not": Array [ + Object { + "exists": Object { + "field": "service.node.name", }, - ], - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, }, - }, + ], }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], + }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries without a service node name fetches cpu chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "processCPUAverage": Object { - "avg": Object { - "field": "system.process.cpu.total.norm.pct", - }, + "aggs": Object { + "processCPUAverage": Object { + "avg": Object { + "field": "system.process.cpu.total.norm.pct", }, - "processCPUMax": Object { - "max": Object { - "field": "system.process.cpu.total.norm.pct", - }, + }, + "processCPUMax": Object { + "max": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUAverage": Object { - "avg": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUAverage": Object { + "avg": Object { + "field": "system.cpu.total.norm.pct", }, - "systemCPUMax": Object { - "max": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUMax": Object { + "max": Object { + "field": "system.cpu.total.norm.pct", }, - "timeseriesData": Object { - "aggs": Object { - "processCPUAverage": Object { - "avg": Object { - "field": "system.process.cpu.total.norm.pct", - }, - }, - "processCPUMax": Object { - "max": Object { - "field": "system.process.cpu.total.norm.pct", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "processCPUAverage": Object { + "avg": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUAverage": Object { - "avg": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "processCPUMax": Object { + "max": Object { + "field": "system.process.cpu.total.norm.pct", }, - "systemCPUMax": Object { - "max": Object { - "field": "system.cpu.total.norm.pct", - }, + }, + "systemCPUAverage": Object { + "avg": Object { + "field": "system.cpu.total.norm.pct", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "systemCPUMax": Object { + "max": Object { + "field": "system.cpu.total.norm.pct", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries without a service node name fetches heap memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "heapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.heap.committed", - }, + "aggs": Object { + "heapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.heap.committed", }, - "heapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.heap.max", - }, + }, + "heapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.heap.max", }, - "heapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.heap.used", - }, + }, + "heapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.heap.used", }, - "timeseriesData": Object { - "aggs": Object { - "heapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.heap.committed", - }, - }, - "heapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.heap.max", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "heapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.heap.committed", }, - "heapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.heap.used", - }, + }, + "heapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.heap.max", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "heapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.heap.used", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries without a service node name fetches memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "memoryUsedAvg": Object { - "avg": Object { - "script": Object { - "lang": "painless", - "source": " + "aggs": Object { + "memoryUsedAvg": Object { + "avg": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -1311,14 +1281,14 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "memoryUsedMax": Object { - "max": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "memoryUsedMax": Object { + "max": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -1335,16 +1305,16 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "timeseriesData": Object { - "aggs": Object { - "memoryUsedAvg": Object { - "avg": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "timeseriesData": Object { + "aggs": Object { + "memoryUsedAvg": Object { + "avg": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -1361,14 +1331,14 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, - "memoryUsedMax": Object { - "max": Object { - "script": Object { - "lang": "painless", - "source": " + }, + "memoryUsedMax": Object { + "max": Object { + "script": Object { + "lang": "painless", + "source": " /* When no limit is specified in the container, docker allows the app as much memory / swap memory as it wants. This number represents the max possible value for the limit field. @@ -1385,233 +1355,233 @@ Object { double used = (double)$('system.process.cgroup.memory.mem.usage.bytes', 0); return used / total; ", - }, }, }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, - }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, + }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "system.process.cgroup.memory.mem.usage.bytes", - }, + }, + Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "system.process.cgroup.memory.mem.usage.bytes", }, - ], - "minimum_should_match": 1, - "should": Array [ - Object { - "exists": Object { - "field": "system.process.cgroup.memory.mem.limit.bytes", - }, + }, + ], + "minimum_should_match": 1, + "should": Array [ + Object { + "exists": Object { + "field": "system.process.cgroup.memory.mem.limit.bytes", }, - Object { - "exists": Object { - "field": "system.memory.total", - }, + }, + Object { + "exists": Object { + "field": "system.memory.total", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries without a service node name fetches non heap memory chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "nonHeapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.non_heap.committed", - }, + "aggs": Object { + "nonHeapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.non_heap.committed", }, - "nonHeapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.non_heap.max", - }, + }, + "nonHeapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.non_heap.max", }, - "nonHeapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.non_heap.used", - }, + }, + "nonHeapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.non_heap.used", }, - "timeseriesData": Object { - "aggs": Object { - "nonHeapMemoryCommitted": Object { - "avg": Object { - "field": "jvm.memory.non_heap.committed", - }, - }, - "nonHeapMemoryMax": Object { - "avg": Object { - "field": "jvm.memory.non_heap.max", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "nonHeapMemoryCommitted": Object { + "avg": Object { + "field": "jvm.memory.non_heap.committed", }, - "nonHeapMemoryUsed": Object { - "avg": Object { - "field": "jvm.memory.non_heap.used", - }, + }, + "nonHeapMemoryMax": Object { + "avg": Object { + "field": "jvm.memory.non_heap.max", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "nonHeapMemoryUsed": Object { + "avg": Object { + "field": "jvm.memory.non_heap.used", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; exports[`metrics queries without a service node name fetches thread count chart data 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "threadCount": Object { - "avg": Object { - "field": "jvm.thread.count", - }, + "aggs": Object { + "threadCount": Object { + "avg": Object { + "field": "jvm.thread.count", }, - "threadCountMax": Object { - "max": Object { - "field": "jvm.thread.count", - }, + }, + "threadCountMax": Object { + "max": Object { + "field": "jvm.thread.count", }, - "timeseriesData": Object { - "aggs": Object { - "threadCount": Object { - "avg": Object { - "field": "jvm.thread.count", - }, - }, - "threadCountMax": Object { - "max": Object { - "field": "jvm.thread.count", - }, + }, + "timeseriesData": Object { + "aggs": Object { + "threadCount": Object { + "avg": Object { + "field": "jvm.thread.count", }, }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "threadCountMax": Object { + "max": Object { + "field": "jvm.thread.count", }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "terms": Object { - "agent.name": Array [ - "java", - "opentelemetry/java", - "otlp/java", - ], - }, + }, + Object { + "terms": Object { + "agent.name": Array [ + "java", + "opentelemetry/java", + "otlp/java", + ], }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": 1, }, + "size": 0, + "track_total_hits": 1, } `; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts index 7c55aa5e29724..389c855a55712 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts @@ -84,50 +84,48 @@ export async function fetchAndTransformGcMetrics({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...serviceNodeNameQuery(serviceNodeName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - { exists: { field: targetField } }, - { terms: { [AGENT_NAME]: JAVA_AGENT_NAMES } }, - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...serviceNodeNameQuery(serviceNodeName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + { exists: { field: targetField } }, + { terms: { [AGENT_NAME]: JAVA_AGENT_NAMES } }, + ], }, - aggs: { - per_pool: { - terms: { - field: `${groupByField}`, - }, - aggs: { - timeseries: { - date_histogram: getMetricsDateHistogramParams({ - start, - end, - metricsInterval: config.metricsInterval, - }), - aggs: { - // get the max value - max: fieldAggregation, - // get the derivative, which is the delta y + }, + aggs: { + per_pool: { + terms: { + field: `${groupByField}`, + }, + aggs: { + timeseries: { + date_histogram: getMetricsDateHistogramParams({ + start, + end, + metricsInterval: config.metricsInterval, + }), + aggs: { + // get the max value + max: fieldAggregation, + // get the derivative, which is the delta y + derivative: { derivative: { - derivative: { - buckets_path: 'max', - }, + buckets_path: 'max', }, - // if a gc counter is reset, the delta will be >0 and - // needs to be excluded - value: { - bucket_script: { - buckets_path: { value: 'derivative' }, - script: 'params.value > 0.0 ? params.value : 0.0', - }, + }, + // if a gc counter is reset, the delta will be >0 and + // needs to be excluded + value: { + bucket_script: { + buckets_path: { value: 'derivative' }, + script: 'params.value > 0.0 ? params.value : 0.0', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts index adccc0af6faa8..5e6c56a6144cc 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts @@ -31,14 +31,12 @@ type MetricsAggregationMap = Unionize<{ type MetricAggs = Record; export type GenericMetricsRequest = APMEventESSearchRequest & { - body: { - aggs: { - timeseriesData: { - date_histogram: AggregationOptionsByType['date_histogram']; - aggs: MetricAggs; - }; - } & MetricAggs; - }; + aggs: { + timeseriesData: { + date_histogram: AggregationOptionsByType['date_histogram']; + aggs: MetricAggs; + }; + } & MetricAggs; }; export type GenericMetricsChart = FetchAndTransformMetrics; @@ -88,32 +86,30 @@ export async function fetchAndTransformMetrics({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: 1, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...serviceNodeNameQuery(serviceNodeName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...additionalFilters, - ], - }, + track_total_hits: 1, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...serviceNodeNameQuery(serviceNodeName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...additionalFilters, + ], }, - aggs: { - timeseriesData: { - date_histogram: getMetricsDateHistogramParams({ - start, - end, - metricsInterval: config.metricsInterval, - }), - aggs, - }, - ...aggs, + }, + aggs: { + timeseriesData: { + date_histogram: getMetricsDateHistogramParams({ + start, + end, + metricsInterval: config.metricsInterval, + }), + aggs, }, + ...aggs, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/get_service_nodes.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/get_service_nodes.ts index 2f3cdb58fcc02..bb703870f6233 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/get_service_nodes.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/get_service_nodes.ts @@ -91,54 +91,52 @@ async function getElasticServiceNodes({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - nodes: { - terms: { - field: SERVICE_NODE_NAME, - size: 10000, - missing: SERVICE_NODE_NAME_MISSING, - }, - aggs: { - latest: { - top_metrics: { - metrics: asMutableArray([{ field: HOST_NAME }] as const), - sort: { - '@timestamp': 'desc' as const, - }, + }, + aggs: { + nodes: { + terms: { + field: SERVICE_NODE_NAME, + size: 10000, + missing: SERVICE_NODE_NAME_MISSING, + }, + aggs: { + latest: { + top_metrics: { + metrics: asMutableArray([{ field: HOST_NAME }] as const), + sort: { + '@timestamp': 'desc' as const, }, }, - cpu: { - avg: { - field: METRIC_PROCESS_CPU_PERCENT, - }, + }, + cpu: { + avg: { + field: METRIC_PROCESS_CPU_PERCENT, }, - heapMemory: { - avg: { - field: METRIC_JAVA_HEAP_MEMORY_USED, - }, + }, + heapMemory: { + avg: { + field: METRIC_JAVA_HEAP_MEMORY_USED, }, - nonHeapMemory: { - avg: { - field: METRIC_JAVA_NON_HEAP_MEMORY_USED, - }, + }, + nonHeapMemory: { + avg: { + field: METRIC_JAVA_NON_HEAP_MEMORY_USED, }, - threadCount: { - max: { - field: METRIC_JAVA_THREAD_COUNT, - }, + }, + threadCount: { + max: { + field: METRIC_JAVA_THREAD_COUNT, }, }, }, @@ -189,68 +187,66 @@ async function getOTelServiceNodes({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - nodes: { - terms: { - field: SERVICE_NODE_NAME, - size: 10000, - missing: SERVICE_NODE_NAME_MISSING, - }, - aggs: { - latest: { - top_metrics: { - metrics: asMutableArray([{ field: HOST_NAME }] as const), - sort: { - '@timestamp': 'desc' as const, - }, + }, + aggs: { + nodes: { + terms: { + field: SERVICE_NODE_NAME, + size: 10000, + missing: SERVICE_NODE_NAME_MISSING, + }, + aggs: { + latest: { + top_metrics: { + metrics: asMutableArray([{ field: HOST_NAME }] as const), + sort: { + '@timestamp': 'desc' as const, }, }, - cpu: { - avg: { - field: METRIC_OTEL_JVM_PROCESS_CPU_PERCENT, - }, + }, + cpu: { + avg: { + field: METRIC_OTEL_JVM_PROCESS_CPU_PERCENT, }, - heapMemory: { - filter: { - term: { [LABEL_TYPE]: VALUE_OTEL_JVM_PROCESS_MEMORY_HEAP }, - }, - aggs: { - usage: { - avg: { - field: METRIC_OTEL_JVM_PROCESS_MEMORY_USAGE, - }, + }, + heapMemory: { + filter: { + term: { [LABEL_TYPE]: VALUE_OTEL_JVM_PROCESS_MEMORY_HEAP }, + }, + aggs: { + usage: { + avg: { + field: METRIC_OTEL_JVM_PROCESS_MEMORY_USAGE, }, }, }, - nonHeapMemory: { - filter: { - term: { [LABEL_TYPE]: VALUE_OTEL_JVM_PROCESS_MEMORY_NON_HEAP }, - }, - aggs: { - usage: { - avg: { - field: METRIC_OTEL_JVM_PROCESS_MEMORY_USAGE, - }, + }, + nonHeapMemory: { + filter: { + term: { [LABEL_TYPE]: VALUE_OTEL_JVM_PROCESS_MEMORY_NON_HEAP }, + }, + aggs: { + usage: { + avg: { + field: METRIC_OTEL_JVM_PROCESS_MEMORY_USAGE, }, }, }, - threadCount: { - max: { - field: METRIC_OTEL_JVM_PROCESS_THREADS_COUNT, - }, + }, + threadCount: { + max: { + field: METRIC_OTEL_JVM_PROCESS_THREADS_COUNT, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/has_otel_metrics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/has_otel_metrics.ts index 52198fc874e01..3e54ce90cdf54 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/has_otel_metrics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/has_otel_metrics.ts @@ -37,32 +37,30 @@ const hasOTelMetrics = async ({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 1, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - { - bool: { - should: [ - { exists: { field: METRIC_OTEL_JVM_PROCESS_CPU_PERCENT } }, - { exists: { field: METRIC_OTEL_JVM_PROCESS_MEMORY_USAGE } }, - { exists: { field: METRIC_OTEL_JVM_PROCESS_THREADS_COUNT } }, - { exists: { field: METRIC_OTEL_SYSTEM_CPU_UTILIZATION } }, - { exists: { field: METRIC_OTEL_SYSTEM_MEMORY_UTILIZATION } }, - ], - }, + track_total_hits: false, + size: 1, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + { + bool: { + should: [ + { exists: { field: METRIC_OTEL_JVM_PROCESS_CPU_PERCENT } }, + { exists: { field: METRIC_OTEL_JVM_PROCESS_MEMORY_USAGE } }, + { exists: { field: METRIC_OTEL_JVM_PROCESS_THREADS_COUNT } }, + { exists: { field: METRIC_OTEL_SYSTEM_CPU_UTILIZATION } }, + { exists: { field: METRIC_OTEL_SYSTEM_MEMORY_UTILIZATION } }, + ], }, - ], - }, + }, + ], }, - _source: false, }, + _source: false, }; const response = await apmEventClient.search('has_otel_process_metrics', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_overview.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_overview.ts index 17aff6da9d8d0..1d83b85549248 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_overview.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_overview.ts @@ -71,50 +71,48 @@ export async function getServerlessActiveInstancesOverview({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: 1, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(METRICSET_NAME, 'app'), - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(FAAS_ID, serverlessId), - ], - }, + track_total_hits: 1, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(METRICSET_NAME, 'app'), + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(FAAS_ID, serverlessId), + ], }, - aggs: { - activeInstances: { - terms: { field: SERVICE_NODE_NAME }, - aggs: { - serverlessFunctions: { - terms: { field: FAAS_ID }, - aggs: { - ...{ - ...aggs, - maxTotalMemory: { - max: { field: METRIC_SYSTEM_TOTAL_MEMORY }, - }, - avgTotalMemory: { - avg: { field: METRIC_SYSTEM_TOTAL_MEMORY }, - }, - avgFreeMemory: { avg: { field: METRIC_SYSTEM_FREE_MEMORY } }, + }, + aggs: { + activeInstances: { + terms: { field: SERVICE_NODE_NAME }, + aggs: { + serverlessFunctions: { + terms: { field: FAAS_ID }, + aggs: { + ...{ + ...aggs, + maxTotalMemory: { + max: { field: METRIC_SYSTEM_TOTAL_MEMORY }, + }, + avgTotalMemory: { + avg: { field: METRIC_SYSTEM_TOTAL_MEMORY }, }, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: start, - max: end, - }, + avgFreeMemory: { avg: { field: METRIC_SYSTEM_FREE_MEMORY } }, + }, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: start, + max: end, }, - aggs, }, + aggs, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_timeseries.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_timeseries.ts index 4efe74df7771c..443f2dc91de19 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_timeseries.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_active_instances_timeseries.ts @@ -50,31 +50,29 @@ export async function getActiveInstancesTimeseries({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(METRICSET_NAME, 'app'), - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(FAAS_ID, serverlessId), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(METRICSET_NAME, 'app'), + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(FAAS_ID, serverlessId), + ], }, - aggs: { - ...aggs, - timeseriesData: { - date_histogram: getMetricsDateHistogramParams({ - start, - end, - metricsInterval: config.metricsInterval, - }), - aggs, - }, + }, + aggs: { + ...aggs, + timeseriesData: { + date_histogram: getMetricsDateHistogramParams({ + start, + end, + metricsInterval: config.metricsInterval, + }), + aggs, }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_compute_usage_chart.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_compute_usage_chart.ts index dda2fbe1c5d56..efd61c39c32b7 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_compute_usage_chart.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_compute_usage_chart.ts @@ -56,33 +56,31 @@ export async function getComputeUsageChart({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - { exists: { field: FAAS_BILLED_DURATION } }, - ...termQuery(METRICSET_NAME, 'app'), - ...termQuery(FAAS_ID, serverlessId), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + { exists: { field: FAAS_BILLED_DURATION } }, + ...termQuery(METRICSET_NAME, 'app'), + ...termQuery(FAAS_ID, serverlessId), + ], }, - aggs: { - timeseriesData: { - date_histogram: getMetricsDateHistogramParams({ - start, - end, - metricsInterval: config.metricsInterval, - }), - aggs, - }, - ...aggs, + }, + aggs: { + timeseriesData: { + date_histogram: getMetricsDateHistogramParams({ + start, + end, + metricsInterval: config.metricsInterval, + }), + aggs, }, + ...aggs, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_functions_overview.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_functions_overview.ts index 6de5977960ef6..fb3b41f8d9943 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_functions_overview.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_functions_overview.ts @@ -50,31 +50,29 @@ export async function getServerlessFunctionsOverview({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(METRICSET_NAME, 'app'), - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(METRICSET_NAME, 'app'), + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - serverlessFunctions: { - terms: { field: FAAS_ID }, - aggs: { - faasDurationAvg: { avg: { field: FAAS_DURATION } }, - faasBilledDurationAvg: { avg: { field: FAAS_BILLED_DURATION } }, - coldStartCount: { sum: { field: FAAS_COLDSTART } }, - maxTotalMemory: { max: { field: METRIC_SYSTEM_TOTAL_MEMORY } }, - avgTotalMemory: { avg: { field: METRIC_SYSTEM_TOTAL_MEMORY } }, - avgFreeMemory: { avg: { field: METRIC_SYSTEM_FREE_MEMORY } }, - }, + }, + aggs: { + serverlessFunctions: { + terms: { field: FAAS_ID }, + aggs: { + faasDurationAvg: { avg: { field: FAAS_DURATION } }, + faasBilledDurationAvg: { avg: { field: FAAS_BILLED_DURATION } }, + coldStartCount: { sum: { field: FAAS_COLDSTART } }, + maxTotalMemory: { max: { field: METRIC_SYSTEM_TOTAL_MEMORY } }, + avgTotalMemory: { avg: { field: METRIC_SYSTEM_TOTAL_MEMORY } }, + avgFreeMemory: { avg: { field: METRIC_SYSTEM_FREE_MEMORY } }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_summary.ts b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_summary.ts index e9e3fe64fcd54..906dda0997839 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_summary.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/metrics/serverless/get_serverless_summary.ts @@ -53,19 +53,17 @@ async function getServerlessTransactionThroughput({ }, ], }, - body: { - track_total_hits: true, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(FAAS_ID, serverlessId), - ], - }, + track_total_hits: true, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(FAAS_ID, serverlessId), + ], }, }, }; @@ -108,34 +106,32 @@ export async function getServerlessSummary({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(METRICSET_NAME, 'app'), - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(FAAS_ID, serverlessId), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(METRICSET_NAME, 'app'), + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(FAAS_ID, serverlessId), + ], }, - aggs: { - totalFunctions: { cardinality: { field: FAAS_ID } }, - faasDurationAvg: { avg: { field: FAAS_DURATION } }, - faasBilledDurationAvg: { avg: { field: FAAS_BILLED_DURATION } }, - avgTotalMemory: { avg: { field: METRIC_SYSTEM_TOTAL_MEMORY } }, - avgFreeMemory: { avg: { field: METRIC_SYSTEM_FREE_MEMORY } }, - countInvocations: { value_count: { field: FAAS_BILLED_DURATION } }, - avgComputeUsageBytesMs: computeUsageAvgScript, - sample: { - top_metrics: { - metrics: [{ field: HOST_ARCHITECTURE }], - sort: [{ '@timestamp': { order: 'desc' as const } }], - }, + }, + aggs: { + totalFunctions: { cardinality: { field: FAAS_ID } }, + faasDurationAvg: { avg: { field: FAAS_DURATION } }, + faasBilledDurationAvg: { avg: { field: FAAS_BILLED_DURATION } }, + avgTotalMemory: { avg: { field: METRIC_SYSTEM_TOTAL_MEMORY } }, + avgFreeMemory: { avg: { field: METRIC_SYSTEM_FREE_MEMORY } }, + countInvocations: { value_count: { field: FAAS_BILLED_DURATION } }, + avgComputeUsageBytesMs: computeUsageAvgScript, + sample: { + top_metrics: { + metrics: [{ field: HOST_ARCHITECTURE }], + sort: [{ '@timestamp': { order: 'desc' as const } }], }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/get_buckets.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/get_buckets.test.ts.snap index 5c8b2ed593e99..f92db63d5b19c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/get_buckets.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/get_buckets.test.ts.snap @@ -5,58 +5,56 @@ Array [ Array [ "get_error_distribution_buckets", Object { + "aggs": Object { + "distribution": Object { + "histogram": Object { + "extended_bounds": Object { + "max": 1528977600000, + "min": 1528113600000, + }, + "field": "@timestamp", + "interval": 10, + "min_doc_count": 0, + }, + }, + }, "apm": Object { "events": Array [ "error", ], }, - "body": Object { - "aggs": Object { - "distribution": Object { - "histogram": Object { - "extended_bounds": Object { - "max": 1528977600000, - "min": 1528113600000, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "error.type": "crash", }, - "field": "@timestamp", - "interval": 10, - "min_doc_count": 0, }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "error.type": "crash", - }, + Object { + "term": Object { + "service.name": "myServiceName", }, - Object { - "term": Object { - "service.name": "myServiceName", - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 1528113600000, - "lte": 1528977600000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, }, }, - Object { - "term": Object { - "service.environment": "prod", - }, + }, + Object { + "term": Object { + "service.environment": "prod", }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, }, ], ] diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/queries.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/queries.test.ts.snap index 447ac8b736338..9c996575aa000 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/queries.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/__snapshots__/queries.test.ts.snap @@ -2,109 +2,105 @@ exports[`error distribution queries fetches an error distribution 1`] = ` Object { + "aggs": Object { + "distribution": Object { + "histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "interval": 3333, + "min_doc_count": 0, + }, + }, + }, "apm": Object { "events": Array [ "error", ], }, - "body": Object { - "aggs": Object { - "distribution": Object { - "histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "error.type": "crash", }, - "field": "@timestamp", - "interval": 3333, - "min_doc_count": 0, }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "error.type": "crash", - }, + Object { + "term": Object { + "service.name": "serviceName", }, - Object { - "term": Object { - "service.name": "serviceName", - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; exports[`error distribution queries fetches an error distribution with a group id 1`] = ` Object { + "aggs": Object { + "distribution": Object { + "histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, + }, + "field": "@timestamp", + "interval": 3333, + "min_doc_count": 0, + }, + }, + }, "apm": Object { "events": Array [ "error", ], }, - "body": Object { - "aggs": Object { - "distribution": Object { - "histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "error.type": "crash", }, - "field": "@timestamp", - "interval": 3333, - "min_doc_count": 0, }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "error.type": "crash", - }, + Object { + "term": Object { + "service.name": "serviceName", }, - Object { - "term": Object { - "service.name": "serviceName", - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "term": Object { - "error.grouping_key": "foo", - }, + }, + Object { + "term": Object { + "error.grouping_key": "foo", }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/get_buckets.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/get_buckets.ts index 32116ebb5b3ff..328ffc9b6751b 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/get_buckets.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/distribution/get_buckets.ts @@ -34,31 +34,29 @@ export async function getBuckets({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(ERROR_TYPE, 'crash'), - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(ERROR_GROUP_ID, groupId), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(ERROR_TYPE, 'crash'), + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(ERROR_GROUP_ID, groupId), + ], }, - aggs: { - distribution: { - histogram: { - field: '@timestamp', - min_doc_count: 0, - interval: bucketSize, - extended_bounds: { - min: start, - max: end, - }, + }, + aggs: { + distribution: { + histogram: { + field: '@timestamp', + min_doc_count: 0, + interval: bucketSize, + extended_bounds: { + min: start, + max: end, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_crash_groups/get_crash_group_main_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_crash_groups/get_crash_group_main_statistics.ts index ceb5a4e389617..6fe9cc3bbe8b8 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_crash_groups/get_crash_group_main_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_crash_groups/get_crash_group_main_statistics.ts @@ -85,44 +85,42 @@ export async function getMobileCrashGroupMainStatistics({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(TRANSACTION_NAME, transactionName), - ...termQuery(TRANSACTION_TYPE, transactionType), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...termQuery(ERROR_TYPE, 'crash'), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(TRANSACTION_NAME, transactionName), + ...termQuery(TRANSACTION_TYPE, transactionType), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...termQuery(ERROR_TYPE, 'crash'), + ...kqlQuery(kuery), + ], }, - aggs: { - crash_groups: { - terms: { - field: ERROR_GROUP_ID, - size: maxNumberOfErrorGroups, - order, - }, - aggs: { - sample: { - top_hits: { - size: 1, - fields: [...requiredFields, ...optionalFields], - _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], - sort: { - [AT_TIMESTAMP]: 'desc', - }, + }, + aggs: { + crash_groups: { + terms: { + field: ERROR_GROUP_ID, + size: maxNumberOfErrorGroups, + order, + }, + aggs: { + sample: { + top_hits: { + size: 1, + fields: [...requiredFields, ...optionalFields], + _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], + sort: { + [AT_TIMESTAMP]: 'desc', }, }, - ...(sortByLatestOccurrence - ? { [maxTimestampAggKey]: { max: { field: AT_TIMESTAMP } } } - : {}), }, + ...(sortByLatestOccurrence + ? { [maxTimestampAggKey]: { max: { field: AT_TIMESTAMP } } } + : {}), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_mobile_crash_group_detailed_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_mobile_crash_group_detailed_statistics.ts index 93d1f91c5c7e0..48aeaa3c86ce7 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_mobile_crash_group_detailed_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/crashes/get_mobile_crash_group_detailed_statistics.ts @@ -59,37 +59,35 @@ export async function getMobileCrashesGroupDetailedStatistics({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termsQuery(ERROR_GROUP_ID, ...groupIds), - ...termsQuery(ERROR_TYPE, 'crash'), - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termsQuery(ERROR_GROUP_ID, ...groupIds), + ...termsQuery(ERROR_TYPE, 'crash'), + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - error_groups: { - terms: { - field: ERROR_GROUP_ID, - size: 500, - }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, - }, + }, + aggs: { + error_groups: { + terms: { + field: ERROR_GROUP_ID, + size: 500, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_detailed_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_detailed_statistics.ts index 9498363b17025..267f1212b45ba 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_detailed_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_detailed_statistics.ts @@ -59,39 +59,37 @@ export async function getMobileErrorGroupDetailedStatistics({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termsQuery(ERROR_GROUP_ID, ...groupIds), - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - must_not: { - term: { 'error.type': 'crash' }, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termsQuery(ERROR_GROUP_ID, ...groupIds), + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], + must_not: { + term: { 'error.type': 'crash' }, }, }, - aggs: { - error_groups: { - terms: { - field: ERROR_GROUP_ID, - size: 500, - }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, - }, + }, + aggs: { + error_groups: { + terms: { + field: ERROR_GROUP_ID, + size: 500, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_main_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_main_statistics.ts index afeea78a43214..53253556ff213 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_main_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_error_group_main_statistics.ts @@ -84,46 +84,44 @@ export async function getMobileErrorGroupMainStatistics({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - must_not: { - term: { 'error.type': 'crash' }, - }, - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(TRANSACTION_NAME, transactionName), - ...termQuery(TRANSACTION_TYPE, transactionType), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], + track_total_hits: false, + size: 0, + query: { + bool: { + must_not: { + term: { 'error.type': 'crash' }, }, + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(TRANSACTION_NAME, transactionName), + ...termQuery(TRANSACTION_TYPE, transactionType), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - error_groups: { - terms: { - field: ERROR_GROUP_ID, - size: maxNumberOfErrorGroups, - order, - }, - aggs: { - sample: { - top_hits: { - size: 1, - fields: [...requiredFields, ...optionalFields], - _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], - sort: { - [AT_TIMESTAMP]: 'desc', - }, + }, + aggs: { + error_groups: { + terms: { + field: ERROR_GROUP_ID, + size: maxNumberOfErrorGroups, + order, + }, + aggs: { + sample: { + top_hits: { + size: 1, + fields: [...requiredFields, ...optionalFields], + _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], + sort: { + [AT_TIMESTAMP]: 'desc', }, }, - ...(sortByLatestOccurrence - ? { [maxTimestampAggKey]: { max: { field: AT_TIMESTAMP } } } - : {}), }, + ...(sortByLatestOccurrence + ? { [maxTimestampAggKey]: { max: { field: AT_TIMESTAMP } } } + : {}), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_errors_terms_by_field.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_errors_terms_by_field.ts index b645d9150af5f..8398bc337943a 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_errors_terms_by_field.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_errors_terms_by_field.ts @@ -39,25 +39,23 @@ export async function getMobileErrorsTermsByField({ apm: { events: [ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { + }, + aggs: { + terms: { terms: { - terms: { - field: fieldName, - size, - }, + field: fieldName, + size, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_http_errors.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_http_errors.ts index 2fcfd586d1683..cefa81d3dab29 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_http_errors.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/errors/get_mobile_http_errors.ts @@ -47,33 +47,31 @@ async function getMobileHttpErrorsTimeseries({ }); const response = await apmEventClient.search('get_mobile_http_errors', { apm: { events: [ProcessorEvent.error] }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...environmentQuery(environment), - ...rangeQuery(start, end), - ...rangeQuery(400, 599, HTTP_RESPONSE_STATUS_CODE), - ...kqlQuery(kuery), - ], - must_not: { - term: { 'error.type': 'crash' }, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...environmentQuery(environment), + ...rangeQuery(start, end), + ...rangeQuery(400, 599, HTTP_RESPONSE_STATUS_CODE), + ...kqlQuery(kuery), + ], + must_not: { + term: { 'error.type': 'crash' }, }, }, - aggs: { - timeseries: { - histogram: { - field: '@timestamp', - min_doc_count: 0, - interval: bucketSize, - extended_bounds: { - min: start, - max: end, - }, + }, + aggs: { + timeseries: { + histogram: { + field: '@timestamp', + min_doc_count: 0, + interval: bucketSize, + extended_bounds: { + min: start, + max: end, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_device_os_app.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_device_os_app.ts index 277abc77dab83..bd5b9379f118a 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_device_os_app.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_device_os_app.ts @@ -46,38 +46,36 @@ export async function getDeviceOSApp({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(TRANSACTION_TYPE, transactionType), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(TRANSACTION_TYPE, transactionType), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - devices: { - terms: { - field: DEVICE_MODEL_IDENTIFIER, - size, - }, + }, + aggs: { + devices: { + terms: { + field: DEVICE_MODEL_IDENTIFIER, + size, }, - osVersions: { - terms: { - field: HOST_OS_VERSION, - size, - }, + }, + osVersions: { + terms: { + field: HOST_OS_VERSION, + size, }, - appVersions: { - terms: { - field: SERVICE_VERSION, - size, - }, + }, + appVersions: { + terms: { + field: SERVICE_VERSION, + size, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_average_launch_time.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_average_launch_time.ts index 339119c544701..4fbb6ea53f21e 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_average_launch_time.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_average_launch_time.ts @@ -64,31 +64,29 @@ async function getAvgLaunchTimeTimeseries({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crash_rate.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crash_rate.ts index 6f3282d6fef1d..7c9081f2f971b 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crash_rate.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crash_rate.ts @@ -70,32 +70,30 @@ async function getMobileCrashTimeseries({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(ERROR_TYPE, 'crash'), - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(ERROR_TYPE, 'crash'), + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crashes_by_location.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crashes_by_location.ts index 59257049b67a9..0f04447f6bcc7 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crashes_by_location.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_crashes_by_location.ts @@ -68,30 +68,28 @@ export async function getCrashesByLocation({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, }, - ...aggs, + aggs, }, + ...aggs, }, }); return { diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_detailed_statistics_by_field.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_detailed_statistics_by_field.ts index 7a4d5bbc6ed0f..edabd1e810638 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_detailed_statistics_by_field.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_detailed_statistics_by_field.ts @@ -74,42 +74,40 @@ async function getMobileDetailedStatisticsByField({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - detailed_statistics: { - terms: { - field, - include: fieldValues, - size: fieldValues.length, - }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: startWithOffset, - max: endWithOffset, - }, + }, + aggs: { + detailed_statistics: { + terms: { + field, + include: fieldValues, + size: fieldValues.length, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: startWithOffset, + max: endWithOffset, }, - aggs: { - latency: { - avg: { - field: TRANSACTION_DURATION, - }, + }, + aggs: { + latency: { + avg: { + field: TRANSACTION_DURATION, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests.ts index ff27e6ffe3c83..582fdf334e8a2 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests.ts @@ -68,34 +68,32 @@ async function getHttpRequestsTimeseries({ const response = await apmEventClient.search('get_http_requests_chart', { apm: { events: [ProcessorEvent.span] }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SPAN_TYPE, MobileSpanType.External), - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(SPAN_TYPE, 'external'), - ...termQuery(TRANSACTION_NAME, transactionName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SPAN_TYPE, MobileSpanType.External), + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(SPAN_TYPE, 'external'), + ...termQuery(TRANSACTION_NAME, transactionName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests_by_location.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests_by_location.ts index e49fd8c5b3d82..c6d4faef20ccd 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests_by_location.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_http_requests_by_location.ts @@ -63,31 +63,29 @@ export async function getHttpRequestsByLocation({ apm: { events: [ProcessorEvent.span], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(SPAN_TYPE, 'external'), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(SPAN_TYPE, 'external'), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_launches_by_location.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_launches_by_location.ts index 009d3447620f3..6a13ca5a70a24 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_launches_by_location.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_launches_by_location.ts @@ -61,30 +61,28 @@ export async function getLaunchesByLocation({ }; const response = await apmEventClient.logEventSearch('get_mobile_location_launches', { - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_main_statistics_by_field.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_main_statistics_by_field.ts index 2ad2f72cc879d..06ad7123dfd46 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_main_statistics_by_field.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_main_statistics_by_field.ts @@ -69,35 +69,33 @@ export async function getMobileMainStatisticsByField({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - main_statistics: { - terms: { - field, - size: 1000, - }, - aggs: { - latency: { - avg: { - field: TRANSACTION_DURATION, - }, + }, + aggs: { + main_statistics: { + terms: { + field, + size: 1000, + }, + aggs: { + latency: { + avg: { + field: TRANSACTION_DURATION, }, - sessions: { - cardinality: { - field: SESSION_ID, - }, + }, + sessions: { + cardinality: { + field: SESSION_ID, }, }, }, @@ -135,31 +133,29 @@ export async function getMobileMainStatisticsByField({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - main_statistics: { - terms: { - field, - size: 1000, - }, - aggs: { - crashes: { - filter: { - term: { - [ERROR_TYPE]: 'crash', - }, + }, + aggs: { + main_statistics: { + terms: { + field, + size: 1000, + }, + aggs: { + crashes: { + filter: { + term: { + [ERROR_TYPE]: 'crash', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions.ts index d2800585b2ad5..f0c3da2ec12c4 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions.ts @@ -70,33 +70,31 @@ async function getSessionTimeseries({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { exists: { field: SESSION_ID } }, - ...termQuery(SERVICE_NAME, serviceName), - ...termQuery(TRANSACTION_NAME, transactionName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { exists: { field: SESSION_ID } }, + ...termQuery(SERVICE_NAME, serviceName), + ...termQuery(TRANSACTION_NAME, transactionName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions_by_location.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions_by_location.ts index 33bd868070ca5..3e748c35765bb 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions_by_location.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_sessions_by_location.ts @@ -69,30 +69,28 @@ export async function getSessionsByLocation({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - }, - aggs, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, }, - ...aggs, + aggs, }, + ...aggs, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_terms_by_field.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_terms_by_field.ts index abb3b32fc9377..07db7b1f7dc78 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_terms_by_field.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_mobile_terms_by_field.ts @@ -39,25 +39,23 @@ export async function getMobileTermsByField({ apm: { events: [ProcessorEvent.transaction], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { + }, + aggs: { + terms: { terms: { - terms: { - field: fieldName, - size, - }, + field: fieldName, + size, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_nct.ts b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_nct.ts index b8b89cea7f50d..0d3a8cea7c283 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_nct.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/mobile/get_nct.ts @@ -39,25 +39,23 @@ export async function getNCT({ }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ], }, - aggs: { - netConnectionTypes: { - terms: { - field: NETWORK_CONNECTION_TYPE, - size, - }, + }, + aggs: { + netConnectionTypes: { + terms: { + field: NETWORK_CONNECTION_TYPE, + size, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_service_count.ts b/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_service_count.ts index 1793b357f7980..24dfe19a2be07 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_service_count.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_service_count.ts @@ -30,16 +30,14 @@ export async function getServiceCount({ ProcessorEvent.metric, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: rangeQuery(start, end), - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: rangeQuery(start, end), }, - aggs: { serviceCount: { cardinality: { field: SERVICE_NAME } } }, }, + aggs: { serviceCount: { cardinality: { field: SERVICE_NAME } } }, }; const { aggregations } = await apmEventClient.search( diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts b/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts index 159dfa3576da3..fa4a7d287623f 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts @@ -36,32 +36,30 @@ export async function getTransactionsPerMinute({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + ], }, - aggs: { - transactionType: { - terms: { - field: TRANSACTION_TYPE, - }, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - }, - aggs: { - throughput: { rate: { unit: 'minute' as const } }, - }, + }, + aggs: { + transactionType: { + terms: { + field: TRANSACTION_TYPE, + }, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + }, + aggs: { + throughput: { rate: { unit: 'minute' as const } }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/has_data.ts b/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/has_data.ts index 30406a9100872..66c9da38438e4 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/has_data.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/observability_overview/has_data.ts @@ -33,10 +33,8 @@ export async function getHasData({ events: [ProcessorEvent.transaction, ProcessorEvent.error, ProcessorEvent.metric], }, terminate_after: 1, - body: { - track_total_hits: 1, - size: 0, - }, + track_total_hits: 1, + size: 0, }; const response = await apmEventClient.search('observability_overview_has_apm_data', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/profiling/get_service_correlation_fields.ts b/x-pack/solutions/observability/plugins/apm/server/routes/profiling/get_service_correlation_fields.ts index 2171b8e27de4a..77bf293058722 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/profiling/get_service_correlation_fields.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/profiling/get_service_correlation_fields.ts @@ -45,36 +45,34 @@ export async function getServiceCorrelationFields({ apm: { sources: [{ documentType, rollupInterval }], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ...environmentQuery(environment), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ...environmentQuery(environment), + ], }, - aggs: { - hostHostNames: { - terms: { - field: HOST_HOSTNAME, - size: 500, - }, + }, + aggs: { + hostHostNames: { + terms: { + field: HOST_HOSTNAME, + size: 500, }, - hostNames: { - terms: { - field: HOST_NAME, - size: 500, - }, + }, + hostNames: { + terms: { + field: HOST_NAME, + size: 500, }, - containerIds: { - terms: { - field: CONTAINER_ID, - size: 500, - }, + }, + containerIds: { + terms: { + field: CONTAINER_ID, + size: 500, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/get_services_counts.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/get_services_counts.ts index 41de4a75c0036..4eafc0c58f22e 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/get_services_counts.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/get_services_counts.ts @@ -42,24 +42,22 @@ export async function getServicesCounts({ // This is an edge case that only effects the count preview label. events: [ProcessorEvent.metric], }, - body: { - track_total_hits: 0, - size: 0, - query: { - bool: { - filter: rangeQuery(start, end), - }, + track_total_hits: 0, + size: 0, + query: { + bool: { + filter: rangeQuery(start, end), }, - aggs: { - service_groups: { - filters: { - filters: serviceGroupsKueryMap, - }, - aggs: { - services_count: { - cardinality: { - field: SERVICE_NAME, - }, + }, + aggs: { + service_groups: { + filters: { + filters: serviceGroupsKueryMap, + }, + aggs: { + services_count: { + cardinality: { + field: SERVICE_NAME, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/lookup_services.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/lookup_services.ts index 49fa60f6b120a..bce0c0ee415a6 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/lookup_services.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_groups/lookup_services.ts @@ -39,31 +39,29 @@ export async function lookupServices({ ProcessorEvent.error, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...rangeQuery(start, end), ...kqlQuery(kuery)], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...rangeQuery(start, end), ...kqlQuery(kuery)], }, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: maxNumberOfServices, - }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - }, + }, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: maxNumberOfServices, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, }, - latest: { - top_metrics: { - metrics: [{ field: AGENT_NAME } as const], - sort: { '@timestamp': 'desc' }, - }, + }, + latest: { + top_metrics: { + metrics: [{ field: AGENT_NAME } as const], + sort: { '@timestamp': 'desc' }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts index 75e451b7a2f57..68dcc163d33c2 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts @@ -66,21 +66,19 @@ export async function fetchServicePathsFromTraceIds({ apm: { events: [ProcessorEvent.span, ProcessorEvent.transaction], }, - body: { - terminate_after: terminateAfter, - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - terms: { - [TRACE_ID]: traceIds, - }, + terminate_after: terminateAfter, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + [TRACE_ID]: traceIds, }, - ...rangeQuery(startRange, endRange), - ], - }, + }, + ...rangeQuery(startRange, endRange), + ], }, }, }; @@ -320,12 +318,9 @@ export async function fetchServicePathsFromTraceIds({ const serviceMapParamsWithAggs = { ...serviceMapParams, - body: { - ...serviceMapParams.body, - size: 1, - terminate_after: numDocsPerShardAllowed, - aggs: serviceMapAggs, - }, + size: 1, + terminate_after: numDocsPerShardAllowed, + aggs: serviceMapAggs, }; const serviceMapFromTraceIdsScriptResponse = await apmEventClient.search( diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_anomalies.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_anomalies.ts index 4e9cbe1a2712f..fd58d263a7884 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_anomalies.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_anomalies.ts @@ -7,7 +7,7 @@ import Boom from '@hapi/boom'; import { sortBy, uniqBy } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { MlAnomalyDetectors } from '@kbn/ml-plugin/server'; import { rangeQuery, wildcardQuery } from '@kbn/observability-plugin/server'; import { getSeverity, ML_ERRORS } from '../../../common/anomaly_detection'; @@ -50,46 +50,44 @@ export async function getServiceAnomalies({ } const params = { - body: { - size: 0, - query: { - bool: { - filter: [ - ...apmMlAnomalyQuery({ - detectorTypes: [AnomalyDetectorType.txLatency], - }), - ...rangeQuery(Math.min(end - 30 * 60 * 1000, start), end, 'timestamp'), - { - terms: { - // Only retrieving anomalies for default transaction types - by_field_value: defaultTransactionTypes, - }, + size: 0, + query: { + bool: { + filter: [ + ...apmMlAnomalyQuery({ + detectorTypes: [AnomalyDetectorType.txLatency], + }), + ...rangeQuery(Math.min(end - 30 * 60 * 1000, start), end, 'timestamp'), + { + terms: { + // Only retrieving anomalies for default transaction types + by_field_value: defaultTransactionTypes, }, - ...wildcardQuery(ML_SERVICE_NAME_FIELD, searchQuery), - ] as estypes.QueryDslQueryContainer[], - }, - }, - aggs: { - services: { - composite: { - size: 5000, - sources: [ - { serviceName: { terms: { field: ML_SERVICE_NAME_FIELD } } }, - { jobId: { terms: { field: 'job_id' } } }, - ] as Array>, }, - aggs: { - metrics: { - top_metrics: { - metrics: [ - { field: 'actual' }, - { field: ML_TRANSACTION_TYPE_FIELD }, - { field: 'result_type' }, - { field: 'record_score' }, - ], - sort: { - record_score: 'desc' as const, - }, + ...wildcardQuery(ML_SERVICE_NAME_FIELD, searchQuery), + ] as estypes.QueryDslQueryContainer[], + }, + }, + aggs: { + services: { + composite: { + size: 5000, + sources: [ + { serviceName: { terms: { field: ML_SERVICE_NAME_FIELD } } }, + { jobId: { terms: { field: 'job_id' } } }, + ] as Array>, + }, + aggs: { + metrics: { + top_metrics: { + metrics: [ + { field: 'actual' }, + { field: ML_TRANSACTION_TYPE_FIELD }, + { field: 'result_type' }, + { field: 'record_score' }, + ], + sort: { + record_score: 'desc' as const, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_dependency_node_info.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_dependency_node_info.ts index 1b09fe9d79fc2..48752572cabea 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_dependency_node_info.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_dependency_node_info.ts @@ -71,32 +71,30 @@ function getServiceMapDependencyNodeInfoForTimeRange({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...getDocumentTypeFilterForServiceDestinationStatistics(true), - { - term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName }, - }, - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ], - }, - }, - aggs: { - ...subAggs, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...getDocumentTypeFilterForServiceDestinationStatistics(true), + { + term: { [SPAN_DESTINATION_SERVICE_RESOURCE]: dependencyName }, }, - aggs: subAggs, + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ], + }, + }, + aggs: { + ...subAggs, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, }, + aggs: subAggs, }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts index 3de35800000eb..6aa7e5a79608d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts @@ -173,34 +173,32 @@ async function getTransactionStats({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...filter, - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - { - terms: { - [TRANSACTION_TYPE]: defaultTransactionTypes, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...filter, + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + { + terms: { + [TRANSACTION_TYPE]: defaultTransactionTypes, }, - ], - }, - }, - aggs: { - duration: { avg: { field: durationField } }, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: start, max: end }, - }, - aggs: { - latency: { avg: { field: durationField } }, }, + ], + }, + }, + aggs: { + duration: { avg: { field: durationField } }, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: start, max: end }, + }, + aggs: { + latency: { avg: { field: durationField } }, }, }, }, @@ -244,26 +242,24 @@ async function getCpuStats({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...filter, { exists: { field: METRIC_SYSTEM_CPU_PERCENT } }], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...filter, { exists: { field: METRIC_SYSTEM_CPU_PERCENT } }], }, - aggs: { - avgCpuUsage: { avg: { field: METRIC_SYSTEM_CPU_PERCENT } }, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: start, max: end }, - }, - aggs: { - cpuAvg: { avg: { field: METRIC_SYSTEM_CPU_PERCENT } }, - }, + }, + aggs: { + avgCpuUsage: { avg: { field: METRIC_SYSTEM_CPU_PERCENT } }, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: start, max: end }, + }, + aggs: { + cpuAvg: { avg: { field: METRIC_SYSTEM_CPU_PERCENT } }, }, }, }, @@ -298,26 +294,24 @@ function getMemoryStats({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...filter, ...additionalFilters], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...filter, ...additionalFilters], }, - aggs: { - avgMemoryUsage: { avg: { script } }, - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { min: start, max: end }, - }, - aggs: { - memoryAvg: { avg: { script } }, - }, + }, + aggs: { + avgMemoryUsage: { avg: { script } }, + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { min: start, max: end }, + }, + aggs: { + memoryAvg: { avg: { script } }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_stats.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_stats.ts index d512f621bcf2a..61f95932c3d05 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_stats.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_service_stats.ts @@ -32,31 +32,29 @@ export async function getServiceStats({ ProcessorEvent.error as const, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...termsQuery(SERVICE_NAME, serviceName), - ...kqlQuery(serviceGroupKuery), - ...kqlQuery(kuery), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...termsQuery(SERVICE_NAME, serviceName), + ...kqlQuery(serviceGroupKuery), + ...kqlQuery(kuery), + ], }, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: maxNumberOfServices, - }, - aggs: { - agent_name: { - terms: { - field: AGENT_NAME, - }, + }, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: maxNumberOfServices, + }, + aggs: { + agent_name: { + terms: { + field: AGENT_NAME, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts index d89c9a7a4ea48..af15715a8b322 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts @@ -78,56 +78,54 @@ export async function getTraceSampleIds({ apm: { events, }, - body: { - track_total_hits: false, - size: 0, - query, - aggs: { - connections: { - composite: { - sources: asMutableArray([ - { - [SPAN_DESTINATION_SERVICE_RESOURCE]: { - terms: { - field: SPAN_DESTINATION_SERVICE_RESOURCE, - missing_bucket: true, - }, + track_total_hits: false, + size: 0, + query, + aggs: { + connections: { + composite: { + sources: asMutableArray([ + { + [SPAN_DESTINATION_SERVICE_RESOURCE]: { + terms: { + field: SPAN_DESTINATION_SERVICE_RESOURCE, + missing_bucket: true, }, }, - { - [SERVICE_NAME]: { - terms: { - field: SERVICE_NAME, - }, + }, + { + [SERVICE_NAME]: { + terms: { + field: SERVICE_NAME, }, }, - { - [SERVICE_ENVIRONMENT]: { - terms: { - field: SERVICE_ENVIRONMENT, - missing_bucket: true, - }, + }, + { + [SERVICE_ENVIRONMENT]: { + terms: { + field: SERVICE_ENVIRONMENT, + missing_bucket: true, }, }, - ] as const), - size: fingerprintBucketSize, - }, - aggs: { - sample: { - sampler: { - shard_size: samplerShardSize, - }, - aggs: { - trace_ids: { - terms: { - field: TRACE_ID, - size: traceIdBucketSize, - execution_hint: 'map' as const, - // remove bias towards large traces by sorting on trace.id - // which will be random-esque - order: { - _key: 'desc' as const, - }, + }, + ] as const), + size: fingerprintBucketSize, + }, + aggs: { + sample: { + sampler: { + shard_size: samplerShardSize, + }, + aggs: { + trace_ids: { + terms: { + field: TRACE_ID, + size: traceIdBucketSize, + execution_hint: 'map' as const, + // remove bias towards large traces by sorting on trace.id + // which will be random-esque + order: { + _key: 'desc' as const, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts b/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts index db1c5e028f449..73f53fd650782 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts @@ -48,19 +48,17 @@ export async function getDerivedServiceAnnotations({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...filter, ...rangeQuery(start, end)], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...filter, ...rangeQuery(start, end)], }, - aggs: { - versions: { - terms: { - field: SERVICE_VERSION, - }, + }, + aggs: { + versions: { + terms: { + field: SERVICE_VERSION, }, }, }, @@ -78,19 +76,17 @@ export async function getDerivedServiceAnnotations({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 1, - query: { - bool: { - filter: [...filter, { term: { [SERVICE_VERSION]: version } }], - }, + track_total_hits: false, + size: 1, + query: { + bool: { + filter: [...filter, { term: { [SERVICE_VERSION]: version } }], }, - sort: { - '@timestamp': 'asc', - }, - fields: requiredFields, }, + sort: { + '@timestamp': 'asc', + }, + fields: requiredFields, }); const event = unflattenKnownApmEventFields( diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts b/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts index 32c3de156faec..8a74142b2b7ce 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts @@ -55,16 +55,15 @@ export function getStoredAnnotations({ }; try { - const response: ESSearchResponse = - (await unwrapEsResponse( - client.search( - { - index: annotationsClient.index, - body, - }, - { meta: true } - ) - )) as any; + const response: ESSearchResponse = (await unwrapEsResponse( + client.search( + { + index: annotationsClient.index, + ...body, + }, + { meta: true } + ) + )) as any; return response.hits.hits.map((hit) => { return { diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_agent.ts b/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_agent.ts index 72c15d2ca66ae..c1ea959935006 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_agent.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_agent.ts @@ -50,45 +50,43 @@ export async function getServiceAgent({ apm: { events: [ProcessorEvent.error, ProcessorEvent.transaction, ProcessorEvent.metric], }, - body: { - track_total_hits: 1, - size: 1, - _source: [AGENT_NAME, SERVICE_RUNTIME_NAME, CLOUD_PROVIDER, CLOUD_SERVICE_NAME], - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - { - exists: { - field: AGENT_NAME, - }, + track_total_hits: 1, + size: 1, + _source: [AGENT_NAME, SERVICE_RUNTIME_NAME, CLOUD_PROVIDER, CLOUD_SERVICE_NAME], + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + { + exists: { + field: AGENT_NAME, }, - ], - should: [ - { - exists: { - field: SERVICE_RUNTIME_NAME, - }, + }, + ], + should: [ + { + exists: { + field: SERVICE_RUNTIME_NAME, }, - { - exists: { - field: CLOUD_PROVIDER, - }, + }, + { + exists: { + field: CLOUD_PROVIDER, }, - { - exists: { - field: CLOUD_SERVICE_NAME, - }, + }, + { + exists: { + field: CLOUD_SERVICE_NAME, }, - ], - }, - }, - fields, - sort: { - _score: { order: 'desc' as const }, + }, + ], }, }, + fields, + sort: { + _score: { order: 'desc' as const }, + }, }; const response = await apmEventClient.search('get_service_agent_name', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts b/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts index 3b11e0e71562d..869a1f0a7308c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts @@ -85,17 +85,15 @@ export async function getServiceInstanceMetadataDetails({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - terminate_after: 1, - size: 1, - query: { - bool: { - filter: filter.concat({ term: { [METRICSET_NAME]: 'app' } }), - }, + track_total_hits: false, + terminate_after: 1, + size: 1, + query: { + bool: { + filter: filter.concat({ term: { [METRICSET_NAME]: 'app' } }), }, - fields, }, + fields, } ); @@ -109,13 +107,11 @@ export async function getServiceInstanceMetadataDetails({ apm: { events: [ProcessorEvent.transaction], }, - body: { - track_total_hits: false, - terminate_after: 1, - size: 1, - query: { bool: { filter } }, - fields, - }, + track_total_hits: false, + terminate_after: 1, + size: 1, + query: { bool: { filter } }, + fields, } ); @@ -131,17 +127,15 @@ export async function getServiceInstanceMetadataDetails({ apm: { events: [getProcessorEventForTransactions(true)], }, - body: { - track_total_hits: false, - terminate_after: 1, - size: 1, - query: { - bool: { - filter: filter.concat(getBackwardCompatibleDocumentTypeFilter(true)), - }, + track_total_hits: false, + terminate_after: 1, + size: 1, + query: { + bool: { + filter: filter.concat(getBackwardCompatibleDocumentTypeFilter(true)), }, - fields, }, + fields, } ); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts index b3ad560b7520a..bbfd805915d98 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts @@ -117,36 +117,34 @@ export async function getServiceInstancesSystemMetricStatistics { expect(internalClientIndexMock).toHaveBeenCalledWith('create_or_update_custom_link', { refresh: 'wait_for', index: '.apm-custom-link', - body: { + document: { '@timestamp': 1570737000000, label: 'foo', url: 'http://elastic.com/{{trace.id}}', @@ -60,7 +60,7 @@ describe('Create or Update Custom link', () => { refresh: 'wait_for', index: '.apm-custom-link', id: 'bar', - body: { + document: { '@timestamp': 1570737000000, label: 'foo', url: 'http://elastic.com/{{trace.id}}', diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts b/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts index edf65d979e60f..62643f76c6dc0 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts @@ -25,7 +25,7 @@ export function createOrUpdateCustomLink({ const params: APMIndexDocumentParams = { refresh: 'wait_for' as const, index: APM_CUSTOM_LINK_INDEX, - body: { + document: { '@timestamp': Date.now(), ...toESFormat(customLink), }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/get_transaction.ts b/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/get_transaction.ts index f1209d4588fd9..66098c67734b4 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/get_transaction.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/get_transaction.ts @@ -40,13 +40,11 @@ export async function getTransaction({ }, ], }, - body: { - track_total_hits: false, - size: 1, - query: { - bool: { - filter: esFilters, - }, + track_total_hits: false, + size: 1, + query: { + bool: { + filter: esFilters, }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts b/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts index abcf100010893..10236cc75f950 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts @@ -6,7 +6,7 @@ */ import type * as t from 'io-ts'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { CustomLink, CustomLinkES } from '../../../../common/custom_link/custom_link_types'; import { fromESFormat } from './helper'; import type { filterOptionsRt } from './custom_link_types'; @@ -35,20 +35,18 @@ export async function listCustomLinks({ const params = { index: APM_CUSTOM_LINK_INDEX, size: 500, - body: { - query: { - bool: { - filter: esFilters, - }, + query: { + bool: { + filter: esFilters, }, - sort: [ - { - 'label.keyword': { - order: 'asc' as const, - }, - }, - ], }, + sort: [ + { + 'label.keyword': { + order: 'asc' as const, + }, + }, + ], }; const resp = await internalESClient.search('list_custom_links', params); const customLinks = resp.hits.hits.map((item) => diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/create_apm_source_map_index_template.ts b/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/create_apm_source_map_index_template.ts index 588e852ac8342..4b8503f50096d 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/create_apm_source_map_index_template.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/create_apm_source_map_index_template.ts @@ -5,48 +5,46 @@ * 2.0. */ -import type { IndicesPutIndexTemplateRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { IndicesPutIndexTemplateRequest } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient, Logger } from '@kbn/core/server'; import { createOrUpdateIndexTemplate } from '@kbn/observability-plugin/server'; import { APM_SOURCE_MAP_INDEX } from '../settings/apm_indices/apm_system_index_constants'; const indexTemplate: IndicesPutIndexTemplateRequest = { name: 'apm-source-map', - body: { - version: 1, - index_patterns: [APM_SOURCE_MAP_INDEX], - template: { - settings: { - index: { - number_of_shards: 1, - auto_expand_replicas: '0-1', - hidden: true, - }, + version: 1, + index_patterns: [APM_SOURCE_MAP_INDEX], + template: { + settings: { + index: { + number_of_shards: 1, + auto_expand_replicas: '0-1', + hidden: true, }, - mappings: { - dynamic: 'strict', - properties: { - fleet_id: { - type: 'keyword', - }, - created: { - type: 'date', - }, - content: { - type: 'binary', - }, - content_sha256: { - type: 'keyword', - }, - 'file.path': { - type: 'keyword', - }, - 'service.name': { - type: 'keyword', - }, - 'service.version': { - type: 'keyword', - }, + }, + mappings: { + dynamic: 'strict', + properties: { + fleet_id: { + type: 'keyword', + }, + created: { + type: 'date', + }, + content: { + type: 'binary', + }, + content_sha256: { + type: 'keyword', + }, + 'file.path': { + type: 'keyword', + }, + 'service.name': { + type: 'keyword', + }, + 'service.version': { + type: 'keyword', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/schedule_source_map_migration.ts b/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/schedule_source_map_migration.ts index 0e18a9b47c37a..44e83a3032f8c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/schedule_source_map_migration.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/source_maps/schedule_source_map_migration.ts @@ -209,10 +209,8 @@ async function getLatestApmSourceMap(internalESClient: ElasticsearchClient) { track_total_hits: false, size: 1, _source: ['created'], - sort: [{ created: { order: 'desc' } }], - body: { - query: { match_all: {} }, - }, + sort: [{ created: { order: 'desc' as const } }], + query: { match_all: {} }, }; const res = await internalESClient.search(params); return res.hits.hits[0]?._source?.created; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_children.ts b/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_children.ts index b78585bffc3ef..8cd432498987e 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_children.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_children.ts @@ -47,18 +47,16 @@ async function fetchLinkedChildrenOfSpan({ events: [ProcessorEvent.span, ProcessorEvent.transaction], }, _source: [SPAN_LINKS], - body: { - fields: [...requiredFields, ...optionalFields], - track_total_hits: false, - size: 1000, - query: { - bool: { - filter: [ - ...rangeQuery(startWithBuffer, endWithBuffer), - { term: { [SPAN_LINKS_TRACE_ID]: traceId } }, - ...(spanId ? [{ term: { [SPAN_LINKS_SPAN_ID]: spanId } }] : []), - ], - }, + fields: [...requiredFields, ...optionalFields], + track_total_hits: false, + size: 1000, + query: { + bool: { + filter: [ + ...rangeQuery(startWithBuffer, endWithBuffer), + { term: { [SPAN_LINKS_TRACE_ID]: traceId } }, + ...(spanId ? [{ term: { [SPAN_LINKS_SPAN_ID]: spanId } }] : []), + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_parents.ts b/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_parents.ts index 741fd80b6eba1..25d25a24ea9d5 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_parents.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_linked_parents.ts @@ -37,21 +37,19 @@ export async function getLinkedParentsOfSpan({ events: [processorEvent], }, _source: [SPAN_LINKS], - body: { - track_total_hits: false, - size: 1, - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - { term: { [TRACE_ID]: traceId } }, - { exists: { field: SPAN_LINKS } }, - { term: { [PROCESSOR_EVENT]: processorEvent } }, - ...(processorEvent === ProcessorEvent.transaction - ? [{ term: { [TRANSACTION_ID]: spanId } }] - : [{ term: { [SPAN_ID]: spanId } }]), - ], - }, + track_total_hits: false, + size: 1, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + { term: { [TRACE_ID]: traceId } }, + { exists: { field: SPAN_LINKS } }, + { term: { [PROCESSOR_EVENT]: processorEvent } }, + ...(processorEvent === ProcessorEvent.transaction + ? [{ term: { [TRANSACTION_ID]: spanId } }] + : [{ term: { [SPAN_ID]: spanId } }]), + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_span_links_details.ts b/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_span_links_details.ts index e118482bf307d..024032ed6e1f6 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_span_links_details.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/span_links/get_span_links_details.ts @@ -75,40 +75,38 @@ async function fetchSpanLinksDetails({ apm: { events: [ProcessorEvent.span, ProcessorEvent.transaction], }, - body: { - fields: [...requiredFields, ...requiredTxFields, ...requiredSpanFields, ...optionalFields], - track_total_hits: false, - size: 1000, - query: { - bool: { - filter: [ - ...rangeQuery(startWithBuffer, endWithBuffer), - ...kqlQuery(kuery), - { - bool: { - should: spanLinks.map((item) => { - return { - bool: { - filter: [ - { term: { [TRACE_ID]: item.trace.id } }, - { - bool: { - should: [ - { term: { [SPAN_ID]: item.span.id } }, - { term: { [TRANSACTION_ID]: item.span.id } }, - ], - minimum_should_match: 1, - }, + fields: [...requiredFields, ...requiredTxFields, ...requiredSpanFields, ...optionalFields], + track_total_hits: false, + size: 1000, + query: { + bool: { + filter: [ + ...rangeQuery(startWithBuffer, endWithBuffer), + ...kqlQuery(kuery), + { + bool: { + should: spanLinks.map((item) => { + return { + bool: { + filter: [ + { term: { [TRACE_ID]: item.trace.id } }, + { + bool: { + should: [ + { term: { [SPAN_ID]: item.span.id } }, + { term: { [TRANSACTION_ID]: item.span.id } }, + ], + minimum_should_match: 1, }, - ], - }, - }; - }), - minimum_should_match: 1, - }, + }, + ], + }, + }; + }), + minimum_should_match: 1, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_service_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_service_statistics.ts index 411e8f35e2867..b80decac781f4 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_service_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_service_statistics.ts @@ -57,68 +57,66 @@ async function getMainServiceStatistics({ ProcessorEvent.metric, ], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: 500, - }, - aggs: { - sample: { - top_metrics: { - size: 1, - metrics: { field: AGENT_NAME }, - sort: { - '@timestamp': 'desc', - }, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: 500, + }, + aggs: { + sample: { + top_metrics: { + size: 1, + metrics: { field: AGENT_NAME }, + sort: { + '@timestamp': 'desc', }, }, - indices: { - terms: { - field: INDEX, - size: 500, - }, - aggs: { - number_of_metric_docs: { - value_count: { - field: INDEX, - }, + }, + indices: { + terms: { + field: INDEX, + size: 500, + }, + aggs: { + number_of_metric_docs: { + value_count: { + field: INDEX, }, }, }, - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - }, + }, + environments: { + terms: { + field: SERVICE_ENVIRONMENT, }, - transactions: { - filter: { - term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction }, - }, - aggs: { - sampled_transactions: { - terms: { - field: TRANSACTION_SAMPLED, - size: 10, - }, + }, + transactions: { + filter: { + term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction }, + }, + aggs: { + sampled_transactions: { + terms: { + field: TRANSACTION_SAMPLED, + size: 10, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_size_timeseries.ts b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_size_timeseries.ts index 86d3c56218361..6d876ca4f82d3 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_size_timeseries.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_size_timeseries.ts @@ -62,52 +62,50 @@ export async function getSizeTimeseries({ ProcessorEvent.metric, ], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: 50, - }, - aggs: { - storageTimeSeries: { - date_histogram: { - field: '@timestamp', - fixed_interval: intervalString, - min_doc_count: 0, - extended_bounds: { - min: start, - max: end, - }, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: 50, + }, + aggs: { + storageTimeSeries: { + date_histogram: { + field: '@timestamp', + fixed_interval: intervalString, + min_doc_count: 0, + extended_bounds: { + min: start, + max: end, }, - aggs: { - indices: { - terms: { - field: INDEX, - size: 500, - }, - aggs: { - number_of_metric_docs_for_index: { - value_count: { - field: INDEX, - }, + }, + aggs: { + indices: { + terms: { + field: INDEX, + size: 500, + }, + aggs: { + number_of_metric_docs_for_index: { + value_count: { + field: INDEX, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_storage_details_per_service.ts b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_storage_details_per_service.ts index a29bc7fa683a7..5c65dceb822a8 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_storage_details_per_service.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_storage_details_per_service.ts @@ -55,47 +55,45 @@ export async function getStorageDetailsPerProcessorEvent({ ProcessorEvent.metric, ], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...termQuery(SERVICE_NAME, serviceName), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...termQuery(SERVICE_NAME, serviceName), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - processor_event: { - terms: { - field: PROCESSOR_EVENT, - size: 10, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + processor_event: { + terms: { + field: PROCESSOR_EVENT, + size: 10, + }, + aggs: { + number_of_metric_docs_for_processor_event: { + value_count: { + field: PROCESSOR_EVENT, + }, }, - aggs: { - number_of_metric_docs_for_processor_event: { - value_count: { - field: PROCESSOR_EVENT, - }, + indices: { + terms: { + field: INDEX, + size: 500, }, - indices: { - terms: { - field: INDEX, - size: 500, - }, - aggs: { - number_of_metric_docs_for_index: { - value_count: { - field: INDEX, - }, + aggs: { + number_of_metric_docs_for_index: { + value_count: { + field: INDEX, }, }, }, @@ -173,36 +171,34 @@ export async function getStorageDetailsPerIndex({ ProcessorEvent.metric, ], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...termQuery(SERVICE_NAME, serviceName), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...termQuery(SERVICE_NAME, serviceName), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - indices: { - terms: { - field: INDEX, - size: 500, - }, - aggs: { - number_of_metric_docs_for_index: { - value_count: { - field: INDEX, - }, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + indices: { + terms: { + field: INDEX, + size: 500, + }, + aggs: { + number_of_metric_docs_for_index: { + value_count: { + field: INDEX, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_summary_statistics.ts b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_summary_statistics.ts index 23f5c4263a3f5..916807a2231b6 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_summary_statistics.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_summary_statistics.ts @@ -55,28 +55,26 @@ async function getTracesPerMinute({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - isRootTransaction(searchAggregatedTransactions), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + isRootTransaction(searchAggregatedTransactions), + ], }, - aggs: { - traces_count: { - value_count: { - field: getDurationFieldForTransactions(searchAggregatedTransactions), - }, + }, + aggs: { + traces_count: { + value_count: { + field: getDurationFieldForTransactions(searchAggregatedTransactions), }, }, }, @@ -117,40 +115,38 @@ async function getMainSummaryStats({ ProcessorEvent.metric, ], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], }, - aggs: { - services_count: { - cardinality: { - field: SERVICE_NAME, - }, + }, + aggs: { + services_count: { + cardinality: { + field: SERVICE_NAME, }, - sample: { - random_sampler: randomSampler, - aggs: { - indices: { - terms: { - field: INDEX, - size: 500, - }, - aggs: { - number_of_metric_docs: { - value_count: { - field: INDEX, - }, + }, + sample: { + random_sampler: randomSampler, + aggs: { + indices: { + terms: { + field: INDEX, + size: 500, + }, + aggs: { + number_of_metric_docs: { + value_count: { + field: INDEX, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_total_transactions_per_service.ts b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_total_transactions_per_service.ts index d895077766e90..8a20745a40edb 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_total_transactions_per_service.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/get_total_transactions_per_service.ts @@ -41,31 +41,29 @@ export async function getTotalTransactionsPerService({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...rangeQuery(start, end), - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...rangeQuery(start, end), + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery(TIER, indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: 500, - }, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: 500, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/has_storage_explorer_privileges.ts b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/has_storage_explorer_privileges.ts index 9fffafc8ff0e8..fcdb6c23dbbe4 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/has_storage_explorer_privileges.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/storage_explorer/has_storage_explorer_privileges.ts @@ -39,15 +39,13 @@ export async function hasStorageExplorerPrivileges({ const esClient = (await context.core).elasticsearch.client; const { index, cluster } = await esClient.asCurrentUser.security.hasPrivileges({ - body: { - index: [ - { - names, - privileges: ['monitor'], - }, - ], - cluster: ['monitor'], - }, + index: [ + { + names, + privileges: ['monitor'], + }, + ], + cluster: ['monitor'], }); const hasPrivileges = cluster.monitor && every(index, 'monitor'); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.test.ts b/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.test.ts index f2a8b9873df1e..f54468d810b47 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.test.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.test.ts @@ -76,11 +76,9 @@ const expectWildcardQueryPresenceInFilters = (params: { const expectation = present ? expect.arrayContaining : expect.not.arrayContaining; return expect.objectContaining({ - body: expect.objectContaining({ - query: expect.objectContaining({ - bool: expect.objectContaining({ - filter: expectation([expect.objectContaining(wildcardQuery)]), - }), + query: expect.objectContaining({ + bool: expect.objectContaining({ + filter: expectation([expect.objectContaining(wildcardQuery)]), }), }), }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.ts b/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.ts index ad33634726249..cdf8296d37653 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/suggestions/get_suggestions_with_terms_aggregation.ts @@ -37,23 +37,21 @@ export async function getSuggestionsWithTermsAggregation({ ProcessorEvent.metric, ], }, - body: { - track_total_hits: false, - timeout: '1500ms', - size: 0, - query: { - bool: { - filter: [ - ...termQuery(SERVICE_NAME, serviceName), - ...rangeQuery(start, end), - ...(fieldName ? wildcardQuery(fieldName, fieldValue) : []), - ], - }, + track_total_hits: false, + timeout: '1500ms', + size: 0, + query: { + bool: { + filter: [ + ...termQuery(SERVICE_NAME, serviceName), + ...rangeQuery(start, end), + ...(fieldName ? wildcardQuery(fieldName, fieldValue) : []), + ], }, - aggs: { - items: { - terms: { field: fieldName, size }, - }, + }, + aggs: { + items: { + terms: { field: fieldName, size }, }, }, }); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/traces/__snapshots__/queries.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/traces/__snapshots__/queries.test.ts.snap index 58ec97112e8f6..90dcfd4d037e1 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/traces/__snapshots__/queries.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/traces/__snapshots__/queries.test.ts.snap @@ -2,6 +2,12 @@ exports[`trace queries fetches a trace 1`] = ` Object { + "_source": Array [ + "error.log.message", + "error.exception.message", + "error.exception.handled", + "error.exception.type", + ], "apm": Object { "sources": Array [ Object { @@ -10,60 +16,52 @@ Object { }, ], }, - "body": Object { - "_source": Array [ - "error.log.message", - "error.exception.message", - "error.exception.handled", - "error.exception.type", - ], - "fields": Array [ - "timestamp.us", - "trace.id", - "service.name", - "error.id", - "error.grouping_key", - "processor.event", - "parent.id", - "transaction.id", - "span.id", - "error.culprit", - "error.log.message", - "error.exception.message", - "error.exception.handled", - "error.exception.type", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "trace.id": "foo", - }, + "fields": Array [ + "timestamp.us", + "trace.id", + "service.name", + "error.id", + "error.grouping_key", + "processor.event", + "parent.id", + "transaction.id", + "span.id", + "error.culprit", + "error.log.message", + "error.exception.message", + "error.exception.handled", + "error.exception.type", + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "trace.id": "foo", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - "must_not": Object { - "terms": Object { - "error.log.level": Array [ - "debug", - "info", - "warning", - ], - }, + }, + ], + "must_not": Object { + "terms": Object { + "error.log.level": Array [ + "debug", + "info", + "warning", + ], }, }, }, - "size": 1000, - "track_total_hits": false, }, + "size": 1000, + "track_total_hits": false, } `; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_aggregated_critical_path.ts b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_aggregated_critical_path.ts index a030cf4e95945..971a853d69908 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_aggregated_critical_path.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_aggregated_critical_path.ts @@ -76,35 +76,34 @@ export async function getAggregatedCriticalPath({ apm: { events: [ProcessorEvent.span, ProcessorEvent.transaction], }, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...termsQuery(TRACE_ID, ...traceIds), - // we need a range query to allow ES to skip shards based on the time range, - // but we need enough padding to make sure we get the full trace - ...rangeQuery(start - TWO_DAYS_MS, end + TWO_DAYS_MS), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...termsQuery(TRACE_ID, ...traceIds), + // we need a range query to allow ES to skip shards based on the time range, + // but we need enough padding to make sure we get the full trace + ...rangeQuery(start - TWO_DAYS_MS, end + TWO_DAYS_MS), + ], }, - aggs: { - critical_path: { - scripted_metric: { - params: { - // can't send null parameters to ES. undefined will be removed during JSON serialisation - serviceName: serviceName || undefined, - transactionName: transactionName || undefined, - }, - init_script: { - source: ` + }, + aggs: { + critical_path: { + scripted_metric: { + params: { + // can't send null parameters to ES. undefined will be removed during JSON serialisation + serviceName: serviceName || undefined, + transactionName: transactionName || undefined, + }, + init_script: { + source: ` state.eventsById = [:]; state.metadataByOperationId = [:]; `, - }, - map_script: { - source: ` + }, + map_script: { + source: ` String toHash (def item) { long FNV_32_INIT = 0x811c9dc5L; long FNV_32_PRIME = 0x01000193L; @@ -164,12 +163,12 @@ export async function getAggregatedCriticalPath({ } state.eventsById.put(id, map); `, - }, - combine_script: { - source: 'return state;', - }, - reduce_script: { - source: ` + }, + combine_script: { + source: 'return state;', + }, + reduce_script: { + source: ` String toHash (def item) { long FNV_32_INIT = 0x811c9dc5L; long FNV_32_PRIME = 0x01000193L; @@ -401,7 +400,6 @@ export async function getAggregatedCriticalPath({ "rootNodes": rootNodes, "operationIdByNodeId": operationIdByNodeId ];`, - }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_top_traces_primary_stats.ts b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_top_traces_primary_stats.ts index c5e82706dd07f..6b43717c77282 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_top_traces_primary_stats.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_top_traces_primary_stats.ts @@ -69,63 +69,61 @@ export async function getTopTracesPrimaryStats({ apm: { events: [getProcessorEventForTransactions(searchAggregatedTransactions)], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...termQuery(TRANSACTION_NAME, transactionName), - ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(kuery), - isRootTransaction(searchAggregatedTransactions), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...termQuery(TRANSACTION_NAME, transactionName), + ...getBackwardCompatibleDocumentTypeFilter(searchAggregatedTransactions), + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(kuery), + isRootTransaction(searchAggregatedTransactions), + ], }, - aggs: { - sample: { - random_sampler: randomSampler, - aggs: { - transaction_groups: { - composite: { - sources: asMutableArray([ - { [SERVICE_NAME]: { terms: { field: SERVICE_NAME } } }, - { - [TRANSACTION_NAME]: { - terms: { field: TRANSACTION_NAME }, - }, + }, + aggs: { + sample: { + random_sampler: randomSampler, + aggs: { + transaction_groups: { + composite: { + sources: asMutableArray([ + { [SERVICE_NAME]: { terms: { field: SERVICE_NAME } } }, + { + [TRANSACTION_NAME]: { + terms: { field: TRANSACTION_NAME }, }, - ] as const), - // traces overview is hardcoded to 10000 - size: 10000, - }, - aggs: { - transaction_type: { - top_metrics: { - sort: { - '@timestamp': 'desc' as const, - }, - metrics: [ - { - field: TRANSACTION_TYPE, - } as const, - { - field: AGENT_NAME, - } as const, - ], + }, + ] as const), + // traces overview is hardcoded to 10000 + size: 10000, + }, + aggs: { + transaction_type: { + top_metrics: { + sort: { + '@timestamp': 'desc' as const, }, + metrics: [ + { + field: TRANSACTION_TYPE, + } as const, + { + field: AGENT_NAME, + } as const, + ], }, + }, + avg: { avg: { - avg: { - field: getDurationFieldForTransactions(searchAggregatedTransactions), - }, + field: getDurationFieldForTransactions(searchAggregatedTransactions), }, + }, + sum: { sum: { - sum: { - field: getDurationFieldForTransactions(searchAggregatedTransactions), - }, + field: getDurationFieldForTransactions(searchAggregatedTransactions), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_items.ts b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_items.ts index 4f6222f9fb8a6..0290873e2ba65 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_items.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_items.ts @@ -7,7 +7,7 @@ import type { Logger } from '@kbn/logging'; import type { SortResults } from '@elastic/elasticsearch/lib/api/types'; -import type { QueryDslQueryContainer, Sort } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer, Sort } from '@elastic/elasticsearch/lib/api/types'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { rangeQuery } from '@kbn/observability-plugin/server'; import { last, omit } from 'lodash'; @@ -118,18 +118,16 @@ export async function getTraceItems({ }, ], }, - body: { - track_total_hits: false, - size: 1000, - query: { - bool: { - filter: [{ term: { [TRACE_ID]: traceId } }, ...rangeQuery(start, end)], - must_not: { terms: { [ERROR_LOG_LEVEL]: excludedLogLevels } }, - }, + track_total_hits: false, + size: 1000, + query: { + bool: { + filter: [{ term: { [TRACE_ID]: traceId } }, ...rangeQuery(start, end)], + must_not: { terms: { [ERROR_LOG_LEVEL]: excludedLogLevels } }, }, - fields: [...requiredFields, ...optionalFields], - _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], }, + fields: [...requiredFields, ...optionalFields], + _source: [ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, ERROR_EXC_HANDLED, ERROR_EXC_TYPE], }); const traceResponsePromise = getTraceDocsPaginated({ @@ -341,7 +339,7 @@ async function getTraceDocsPerPage({ apm: { events: [ProcessorEvent.span, ProcessorEvent.transaction], }, - body, + ...body, }); return { diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_samples_by_query.ts b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_samples_by_query.ts index 241f5e3d6db1f..0c989822b3cae 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_samples_by_query.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/traces/get_trace_samples_by_query.ts @@ -50,25 +50,23 @@ export async function getTraceSamplesByQuery({ apm: { events: [ProcessorEvent.transaction, ProcessorEvent.span, ProcessorEvent.error], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - ...environmentQuery(environment), - ...kqlQuery(query), - ], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + ...environmentQuery(environment), + ...kqlQuery(query), + ], }, - aggs: { - traceId: { - terms: { - field: TRACE_ID, - execution_hint: 'map', - size, - }, + }, + aggs: { + traceId: { + terms: { + field: TRACE_ID, + execution_hint: 'map', + size, }, }, }, @@ -104,37 +102,35 @@ export async function getTraceSamplesByQuery({ apm: { events: [ProcessorEvent.transaction], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - term: { - [TRANSACTION_SAMPLED]: true, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + term: { + [TRANSACTION_SAMPLED]: true, }, - ...termsQuery(TRACE_ID, ...traceIds), - ...rangeQuery(start, end), - ], - must_not: [{ exists: { field: PARENT_ID } }], - }, - }, - aggs: { - transactionId: { - terms: { - field: TRANSACTION_ID, - size, }, - aggs: { - latest: { - top_metrics: { - metrics: asMutableArray([{ field: TRACE_ID }] as const), - size: 1, - sort: { - '@timestamp': 'desc' as const, - }, + ...termsQuery(TRACE_ID, ...traceIds), + ...rangeQuery(start, end), + ], + must_not: [{ exists: { field: PARENT_ID } }], + }, + }, + aggs: { + transactionId: { + terms: { + field: TRANSACTION_ID, + size, + }, + aggs: { + latest: { + top_metrics: { + metrics: asMutableArray([{ field: TRACE_ID }] as const), + size: 1, + sort: { + '@timestamp': 'desc' as const, }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/__snapshots__/queries.test.ts.snap b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/__snapshots__/queries.test.ts.snap index 46ea360339f6a..afd61f9260b7e 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/__snapshots__/queries.test.ts.snap +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/__snapshots__/queries.test.ts.snap @@ -2,6 +2,10 @@ exports[`transaction queries fetches a transaction 1`] = ` Object { + "_source": Array [ + "span.links", + "transaction.agent.marks", + ], "apm": Object { "sources": Array [ Object { @@ -10,315 +14,305 @@ Object { }, ], }, - "body": Object { - "_source": Array [ - "span.links", - "transaction.agent.marks", - ], - "fields": Array [ - "trace.id", - "agent.name", - "processor.event", - "@timestamp", - "timestamp.us", - "service.name", - "transaction.id", - "transaction.duration.us", - "transaction.name", - "transaction.sampled", - "transaction.type", - "processor.name", - "service.language.name", - "url.full", - "transaction.page.url", - "http.response.status_code", - "http.request.method", - "user_agent.name", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "transaction.id": "foo", - }, + "fields": Array [ + "trace.id", + "agent.name", + "processor.event", + "@timestamp", + "timestamp.us", + "service.name", + "transaction.id", + "transaction.duration.us", + "transaction.name", + "transaction.sampled", + "transaction.type", + "processor.name", + "service.language.name", + "url.full", + "transaction.page.url", + "http.response.status_code", + "http.request.method", + "user_agent.name", + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "transaction.id": "foo", }, - Object { - "term": Object { - "trace.id": "bar", - }, + }, + Object { + "term": Object { + "trace.id": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - ], - }, + }, + ], }, - "size": 1, - "terminate_after": 1, - "track_total_hits": false, }, + "size": 1, + "terminate_after": 1, + "track_total_hits": false, } `; exports[`transaction queries fetches breakdown data for transactions 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "by_date": Object { - "aggs": Object { - "sum_all_self_times": Object { - "sum": Object { - "field": "span.self_time.sum.us", - }, + "aggs": Object { + "by_date": Object { + "aggs": Object { + "sum_all_self_times": Object { + "sum": Object { + "field": "span.self_time.sum.us", }, - "types": Object { - "aggs": Object { - "subtypes": Object { - "aggs": Object { - "total_self_time_per_subtype": Object { - "sum": Object { - "field": "span.self_time.sum.us", - }, - }, - }, - "terms": Object { - "field": "span.subtype", - "missing": "", - "order": Object { - "_count": "desc", + }, + "types": Object { + "aggs": Object { + "subtypes": Object { + "aggs": Object { + "total_self_time_per_subtype": Object { + "sum": Object { + "field": "span.self_time.sum.us", }, - "size": 20, }, }, - }, - "terms": Object { - "field": "span.type", - "order": Object { - "_count": "desc", + "terms": Object { + "field": "span.subtype", + "missing": "", + "order": Object { + "_count": "desc", + }, + "size": 20, }, - "size": 20, }, }, - }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "terms": Object { + "field": "span.type", + "order": Object { + "_count": "desc", + }, + "size": 20, }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, - "sum_all_self_times": Object { - "sum": Object { - "field": "span.self_time.sum.us", + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, }, - "types": Object { - "aggs": Object { - "subtypes": Object { - "aggs": Object { - "total_self_time_per_subtype": Object { - "sum": Object { - "field": "span.self_time.sum.us", - }, + }, + "sum_all_self_times": Object { + "sum": Object { + "field": "span.self_time.sum.us", + }, + }, + "types": Object { + "aggs": Object { + "subtypes": Object { + "aggs": Object { + "total_self_time_per_subtype": Object { + "sum": Object { + "field": "span.self_time.sum.us", }, }, - "terms": Object { - "field": "span.subtype", - "missing": "", - "order": Object { - "_count": "desc", - }, - "size": 20, + }, + "terms": Object { + "field": "span.subtype", + "missing": "", + "order": Object { + "_count": "desc", }, + "size": 20, }, }, - "terms": Object { - "field": "span.type", - "order": Object { - "_count": "desc", - }, - "size": 20, + }, + "terms": Object { + "field": "span.type", + "order": Object { + "_count": "desc", }, + "size": 20, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "transaction.type": "bar", - }, + }, + Object { + "term": Object { + "transaction.type": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "exists": Object { - "field": "span.self_time.sum.us", - }, + }, + Object { + "exists": Object { + "field": "span.self_time.sum.us", }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; exports[`transaction queries fetches breakdown data for transactions for a transaction name 1`] = ` Object { - "apm": Object { - "events": Array [ - "metric", - ], - }, - "body": Object { - "aggs": Object { - "by_date": Object { - "aggs": Object { - "sum_all_self_times": Object { - "sum": Object { - "field": "span.self_time.sum.us", - }, + "aggs": Object { + "by_date": Object { + "aggs": Object { + "sum_all_self_times": Object { + "sum": Object { + "field": "span.self_time.sum.us", }, - "types": Object { - "aggs": Object { - "subtypes": Object { - "aggs": Object { - "total_self_time_per_subtype": Object { - "sum": Object { - "field": "span.self_time.sum.us", - }, - }, - }, - "terms": Object { - "field": "span.subtype", - "missing": "", - "order": Object { - "_count": "desc", + }, + "types": Object { + "aggs": Object { + "subtypes": Object { + "aggs": Object { + "total_self_time_per_subtype": Object { + "sum": Object { + "field": "span.self_time.sum.us", }, - "size": 20, }, }, - }, - "terms": Object { - "field": "span.type", - "order": Object { - "_count": "desc", + "terms": Object { + "field": "span.subtype", + "missing": "", + "order": Object { + "_count": "desc", + }, + "size": 20, }, - "size": 20, }, }, - }, - "date_histogram": Object { - "extended_bounds": Object { - "max": 50000, - "min": 0, + "terms": Object { + "field": "span.type", + "order": Object { + "_count": "desc", + }, + "size": 20, }, - "field": "@timestamp", - "fixed_interval": "30s", - "min_doc_count": 0, }, }, - "sum_all_self_times": Object { - "sum": Object { - "field": "span.self_time.sum.us", + "date_histogram": Object { + "extended_bounds": Object { + "max": 50000, + "min": 0, }, + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 0, }, - "types": Object { - "aggs": Object { - "subtypes": Object { - "aggs": Object { - "total_self_time_per_subtype": Object { - "sum": Object { - "field": "span.self_time.sum.us", - }, + }, + "sum_all_self_times": Object { + "sum": Object { + "field": "span.self_time.sum.us", + }, + }, + "types": Object { + "aggs": Object { + "subtypes": Object { + "aggs": Object { + "total_self_time_per_subtype": Object { + "sum": Object { + "field": "span.self_time.sum.us", }, }, - "terms": Object { - "field": "span.subtype", - "missing": "", - "order": Object { - "_count": "desc", - }, - "size": 20, + }, + "terms": Object { + "field": "span.subtype", + "missing": "", + "order": Object { + "_count": "desc", }, + "size": 20, }, }, - "terms": Object { - "field": "span.type", - "order": Object { - "_count": "desc", - }, - "size": 20, + }, + "terms": Object { + "field": "span.type", + "order": Object { + "_count": "desc", }, + "size": 20, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + }, + "apm": Object { + "events": Array [ + "metric", + ], + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "transaction.type": "bar", - }, + }, + Object { + "term": Object { + "transaction.type": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "exists": Object { - "field": "span.self_time.sum.us", - }, + }, + Object { + "exists": Object { + "field": "span.self_time.sum.us", }, - Object { - "term": Object { - "transaction.name": "baz", - }, + }, + Object { + "term": Object { + "transaction.name": "baz", }, - ], - }, + }, + ], }, - "size": 0, - "track_total_hits": false, }, + "size": 0, + "track_total_hits": false, } `; @@ -334,73 +328,71 @@ Object { "transaction", ], }, - "body": Object { - "fields": Array [ - "transaction.id", - "trace.id", - "@timestamp", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "foo", - }, + "fields": Array [ + "transaction.id", + "trace.id", + "@timestamp", + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "service.name": "foo", }, - Object { - "term": Object { - "transaction.type": "baz", - }, + }, + Object { + "term": Object { + "transaction.type": "baz", }, - Object { - "term": Object { - "transaction.name": "bar", - }, + }, + Object { + "term": Object { + "transaction.name": "bar", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "term": Object { - "transaction.sampled": true, - }, + }, + Object { + "term": Object { + "transaction.sampled": true, }, - ], - "should": Array [ - Object { - "term": Object { - "trace.id": "qux", - }, + }, + ], + "should": Array [ + Object { + "term": Object { + "trace.id": "qux", }, - Object { - "term": Object { - "transaction.id": "quz", - }, + }, + Object { + "term": Object { + "transaction.id": "quz", }, - ], - }, - }, - "size": 500, - "sort": Array [ - Object { - "_score": Object { - "order": "desc", }, + ], + }, + }, + "size": 500, + "sort": Array [ + Object { + "_score": Object { + "order": "desc", }, - Object { - "@timestamp": Object { - "order": "desc", - }, + }, + Object { + "@timestamp": Object { + "order": "desc", }, - ], - "track_total_hits": false, - }, + }, + ], + "track_total_hits": false, } `; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/breakdown/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/breakdown/index.ts index 9d139c90ade16..5885a1857a29c 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/breakdown/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/breakdown/index.ts @@ -107,24 +107,22 @@ export async function getTransactionBreakdown({ apm: { events: [ProcessorEvent.metric], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: filters, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: filters, }, - aggs: { - ...subAggs, - by_date: { - date_histogram: getMetricsDateHistogramParams({ - start, - end, - metricsInterval: config.metricsInterval, - }), - aggs: subAggs, - }, + }, + aggs: { + ...subAggs, + by_date: { + date_histogram: getMetricsDateHistogramParams({ + start, + end, + metricsInterval: config.metricsInterval, + }), + aggs: subAggs, }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_latency_charts/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_latency_charts/index.ts index c305ece61769a..8ba492a7457a3 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_latency_charts/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_latency_charts/index.ts @@ -76,36 +76,34 @@ function searchLatency({ apm: { sources: [{ documentType, rollupInterval }], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(startWithOffset, endWithOffset), - ...environmentQuery(environment), - ...kqlQuery(kuery), - ...termQuery(TRANSACTION_NAME, transactionName), - ...termQuery(TRANSACTION_TYPE, transactionType), - ...termQuery(FAAS_ID, serverlessId), - ...(filters?.filter || []), - ], - must_not: filters?.must_not || [], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(startWithOffset, endWithOffset), + ...environmentQuery(environment), + ...kqlQuery(kuery), + ...termQuery(TRANSACTION_NAME, transactionName), + ...termQuery(TRANSACTION_TYPE, transactionType), + ...termQuery(FAAS_ID, serverlessId), + ...(filters?.filter || []), + ], + must_not: filters?.must_not || [], }, - aggs: { - latencyTimeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: `${bucketSizeInSeconds}s`, - min_doc_count: 0, - extended_bounds: { min: startWithOffset, max: endWithOffset }, - }, - aggs: getLatencyAggregation(latencyAggregationType, transactionDurationField), + }, + aggs: { + latencyTimeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: `${bucketSizeInSeconds}s`, + min_doc_count: 0, + extended_bounds: { min: startWithOffset, max: endWithOffset }, }, - overall_avg_duration: { avg: { field: transactionDurationField } }, + aggs: getLatencyAggregation(latencyAggregationType, transactionDurationField), }, + overall_avg_duration: { avg: { field: transactionDurationField } }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_span/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_span/index.ts index 6e7161f09227a..6eabd5e5bc579 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_span/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_span/index.ts @@ -38,20 +38,18 @@ export async function getSpan({ apm: { events: [ProcessorEvent.span], }, - body: { - track_total_hits: false, - size: 1, - terminate_after: 1, - fields: ['*'], - _source: [SPAN_STACKTRACE], - query: { - bool: { - filter: asMutableArray([ - { term: { [SPAN_ID]: spanId } }, - ...termQuery(TRACE_ID, traceId), - ...rangeQuery(start, end), - ]), - }, + track_total_hits: false, + size: 1, + terminate_after: 1, + fields: ['*'], + _source: [SPAN_STACKTRACE], + query: { + bool: { + filter: asMutableArray([ + { term: { [SPAN_ID]: spanId } }, + ...termQuery(TRACE_ID, traceId), + ...rangeQuery(start, end), + ]), }, }, }), diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction/index.ts index d40c88ed3d53b..ed8af6b648be6 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction/index.ts @@ -82,22 +82,20 @@ export async function getTransaction({ }, ], }, - body: { - track_total_hits: false, - size: 1, - terminate_after: 1, - query: { - bool: { - filter: asMutableArray([ - { term: { [TRANSACTION_ID]: transactionId } }, - ...termQuery(TRACE_ID, traceId), - ...rangeQuery(start, end), - ]), - }, + track_total_hits: false, + size: 1, + terminate_after: 1, + query: { + bool: { + filter: asMutableArray([ + { term: { [TRANSACTION_ID]: transactionId } }, + ...termQuery(TRACE_ID, traceId), + ...rangeQuery(start, end), + ]), }, - fields: [...requiredFields, ...optionalFields], - _source: [SPAN_LINKS, TRANSACTION_AGENT_MARKS], }, + fields: [...requiredFields, ...optionalFields], + _source: [SPAN_LINKS, TRANSACTION_AGENT_MARKS], }); const hit = maybe(resp.hits.hits[0]); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_name/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_name/index.ts index 50589033bb859..25e486dbc2ea2 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_name/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_name/index.ts @@ -55,21 +55,19 @@ export async function getTransactionByName({ }, ], }, - body: { - track_total_hits: false, - size: 1, - terminate_after: 1, - query: { - bool: { - filter: asMutableArray([ - { term: { [TRANSACTION_NAME]: transactionName } }, - { term: { [SERVICE_NAME]: serviceName } }, - ...rangeQuery(start, end), - ]), - }, + track_total_hits: false, + size: 1, + terminate_after: 1, + query: { + bool: { + filter: asMutableArray([ + { term: { [TRANSACTION_NAME]: transactionName } }, + { term: { [SERVICE_NAME]: serviceName } }, + ...rangeQuery(start, end), + ]), }, - fields: requiredFields, }, + fields: requiredFields, }); return unflattenKnownApmEventFields(maybe(resp.hits.hits[0])?.fields, requiredFields); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts index e2a361d1b1aee..2fdd38e606a24 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts @@ -68,28 +68,26 @@ export async function getRootTransactionByTraceId({ apm: { events: [ProcessorEvent.transaction as const], }, - body: { - track_total_hits: false, - size: 1, - terminate_after: 1, - query: { - bool: { - should: [ - { - constant_score: { - filter: { - bool: { - must_not: { exists: { field: PARENT_ID } }, - }, + track_total_hits: false, + size: 1, + terminate_after: 1, + query: { + bool: { + should: [ + { + constant_score: { + filter: { + bool: { + must_not: { exists: { field: PARENT_ID } }, }, }, }, - ], - filter: [{ term: { [TRACE_ID]: traceId } }, ...rangeQuery(start, end)], - }, + }, + ], + filter: [{ term: { [TRACE_ID]: traceId } }, ...rangeQuery(start, end)], }, - fields: requiredFields, }, + fields: requiredFields, }; const resp = await apmEventClient.search('get_root_transaction_by_trace_id', params); diff --git a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/trace_samples/index.ts b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/trace_samples/index.ts index 8b9f18f43092b..64ec5a84f3df2 100644 --- a/x-pack/solutions/observability/plugins/apm/server/routes/transactions/trace_samples/index.ts +++ b/x-pack/solutions/observability/plugins/apm/server/routes/transactions/trace_samples/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { Sort, QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { Sort, QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; import { kqlQuery, rangeQuery } from '@kbn/observability-plugin/server'; import { unflattenKnownApmEventFields } from '@kbn/apm-data-access-plugin/server/utils'; @@ -87,32 +87,30 @@ export async function getTraceSamples({ events: [ProcessorEvent.transaction], }, _source: [TRANSACTION_ID, TRACE_ID, '@timestamp'], - body: { - track_total_hits: false, - query: { - bool: { - filter: [...commonFilters, { term: { [TRANSACTION_SAMPLED]: true } }], - should: [ - { term: { [TRACE_ID]: traceId } }, - { term: { [TRANSACTION_ID]: transactionId } }, - ] as QueryDslQueryContainer[], - }, + track_total_hits: false, + query: { + bool: { + filter: [...commonFilters, { term: { [TRANSACTION_SAMPLED]: true } }], + should: [ + { term: { [TRACE_ID]: traceId } }, + { term: { [TRANSACTION_ID]: transactionId } }, + ] as QueryDslQueryContainer[], }, - size: TRACE_SAMPLES_SIZE, - fields: requiredFields, - sort: [ - { - _score: { - order: 'desc', - }, + }, + size: TRACE_SAMPLES_SIZE, + fields: requiredFields, + sort: [ + { + _score: { + order: 'desc', }, - { - [AT_TIMESTAMP]: { - order: 'desc', - }, + }, + { + [AT_TIMESTAMP]: { + order: 'desc', }, - ] as Sort, - }, + }, + ] as Sort, }); const traceSamples = response.hits.hits.map((hit) => { diff --git a/x-pack/solutions/observability/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts b/x-pack/solutions/observability/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts index 6f5738fce202f..f0c34b711c131 100644 --- a/x-pack/solutions/observability/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts +++ b/x-pack/solutions/observability/plugins/apm/server/test_helpers/create_apm_users/helpers/create_custom_role.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { omit } from 'lodash'; import type { Elasticsearch, Kibana } from '../create_apm_users'; import { callKibana } from './call_kibana'; @@ -27,7 +27,7 @@ export async function createCustomRole({ // the security API. They are preserved when updating the role below if ('applications' in role) { const esClient = getEsClient(elasticsearch); - await esClient.security.putRole({ name: roleName, body: role }); + await esClient.security.putRole({ name: roleName, ...role }); } await callKibana({ @@ -58,6 +58,7 @@ export function getEsClient(elasticsearch: Elasticsearch) { username, password, }, + Connection: HttpConnection, }); return client; diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/get_request_base.test.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/get_request_base.test.ts index 09fca8ab2331b..3ef1f017a94e2 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/get_request_base.test.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/get_request_base.test.ts @@ -14,10 +14,8 @@ describe('getRequestBase', () => { beforeEach(() => { const request = { apm: { events: ['transaction', 'error'] }, - body: { - track_total_hits: false, - size: 0, - }, + track_total_hits: false, + size: 0, } as APMEventESSearchRequest; const indices = { diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts index 788a2298b5838..2ef80d75f9c9e 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts @@ -8,7 +8,7 @@ import { setTimeout as setTimeoutPromise } from 'timers/promises'; import { contextServiceMock, executionContextServiceMock } from '@kbn/core/server/mocks'; import { createHttpService } from '@kbn/core-http-server-mocks'; import type { ElasticsearchClient, KibanaRequest } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TermsEnumRequest, MsearchMultisearchBody, @@ -81,7 +81,8 @@ describe('APMEventClient', () => { apm: { events: [], }, - body: { size: 0, track_total_hits: false }, + size: 0, + track_total_hits: false, }); return res.ok({ body: 'ok' }); @@ -173,16 +174,14 @@ describe('APMEventClient', () => { await apmEventClient.search('testOperation', { apm: { events: [] }, - body: { - size: 0, - track_total_hits: false, - query: { bool: { filter: [{ match_all: {} }] } }, - }, + size: 0, + track_total_hits: false, + query: { bool: { filter: [{ match_all: {} }] } }, }); const searchParams = esClientMock.search.mock.calls[0][0] as APMEventESSearchRequest; - expect(searchParams.body.query?.bool).toEqual({ + expect(searchParams.query?.bool).toEqual({ filter: [ { terms: { 'processor.event': [] } }, { bool: { must_not: [{ terms: { _tier: ['data_warm', 'data_cold'] } }] } }, @@ -196,11 +195,9 @@ describe('APMEventClient', () => { await apmEventClient.msearch('testOperation', { apm: { events: [] }, - body: { - size: 0, - track_total_hits: false, - query: { bool: { filter: [{ match_all: {} }] } }, - }, + size: 0, + track_total_hits: false, + query: { bool: { filter: [{ match_all: {} }] } }, }); const msearchParams = esClientMock.msearch.mock.calls[0][0] as { diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.ts index 4132b9e277d46..3ed01664a218f 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/create_es_client/create_apm_event_client/index.ts @@ -14,7 +14,7 @@ import type { TermsEnumRequest, TermsEnumResponse, } from '@elastic/elasticsearch/lib/api/types'; -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient, KibanaRequest } from '@kbn/core/server'; import type { InferSearchResponseOf } from '@kbn/es-types'; import { ProcessorEvent } from '@kbn/observability-plugin/common'; @@ -38,17 +38,13 @@ export type APMEventESSearchRequest = Omit & { apm: { includeLegacyData?: boolean; } & ({ events: ProcessorEvent[] } | { sources: ApmDataSource[] }); - body: { - size: number; - track_total_hits: boolean | number; - }; + size: number; + track_total_hits: boolean | number; }; export type APMLogEventESSearchRequest = Omit & { - body: { - size: number; - track_total_hits: boolean | number; - }; + size: number; + track_total_hits: boolean | number; }; type APMEventWrapper = Omit & { @@ -175,15 +171,13 @@ export class APMEventClient { const searchParams = { ...omit(params, 'apm', 'body'), index, - body: { - ...params.body, - query: { - bool: { - filter: filters, - must: compact([params.body.query]), - }, + query: { + bool: { + filter: filters, + must: compact([params.query]), }, }, + body: params.body, ...(this.includeFrozen ? { ignore_throttled: false } : {}), ignore_unavailable: true, preference: 'any', @@ -214,13 +208,11 @@ export class APMEventClient { const searchParams = { ...omit(params, 'body'), index, - body: { - ...params.body, - query: { - bool: { - filter, - must: compact([params.body.query]), - }, + body: params.body, + query: { + bool: { + filter, + must: compact([params.query]), }, }, ...(this.includeFrozen ? { ignore_throttled: false } : {}), @@ -265,10 +257,10 @@ export class APMEventClient { }, { ...omit(params, 'apm', 'body'), - ...params.body, + body: params.body, query: { bool: { - filter: compact([params.body.query, ...filters]), + filter: compact([params.query, ...filters]), }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/tier_filter.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/tier_filter.ts index 83171dea7f444..323a02bf3e4dd 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/tier_filter.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/tier_filter.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { DataTier } from '@kbn/observability-shared-plugin/common'; import { excludeTiersQuery } from '@kbn/observability-utils-common/es/queries/exclude_tiers_query'; diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/transactions/index.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/transactions/index.ts index 8e360dce2cdb3..098c92aa35675 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/transactions/index.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/lib/helpers/transactions/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { TRANSACTION_DURATION_HISTOGRAM, METRICSET_INTERVAL, diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_document_sources/get_document_sources.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_document_sources/get_document_sources.ts index 4491b679f7198..978a5b4e6d115 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_document_sources/get_document_sources.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_document_sources/get_document_sources.ts @@ -5,7 +5,7 @@ * 2.0. */ import { kqlQuery, rangeQuery } from '@kbn/observability-plugin/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { RollupInterval } from '../../../common/rollup'; import type { TimeRangeMetadata } from '../../../common/time_range_metadata'; import { isDurationSummaryNotSupportedFilter } from '../../lib/helpers/transactions'; @@ -36,7 +36,7 @@ const getRequest = ({ rollupInterval: RollupInterval; filters: estypes.QueryDslQueryContainer[]; }) => { - const searchParams = { + return { apm: { sources: [ { @@ -45,20 +45,12 @@ const getRequest = ({ }, ], }, - body: { - track_total_hits: 1, - size: 0, - terminate_after: 1, - }, - }; - return { - ...searchParams, - body: { - ...searchParams.body, - query: { - bool: { - filter: filters, - }, + track_total_hits: 1, + size: 0, + terminate_after: 1, + query: { + bool: { + filter: filters, }, }, }; diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_names/index.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_names/index.ts index f51bcb502190a..345d406ec4c01 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_names/index.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_names/index.ts @@ -43,22 +43,20 @@ export function createGetHostNames({ apmEventClient }: ApmDataAccessServicesPara }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [...castArray(query), ...rangeQuery(start, end)], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [...castArray(query), ...rangeQuery(start, end)], }, - aggs: { - hostNames: { - terms: { - field: HOST_NAME, - size: Math.min(size, MAX_SIZE), - order: { - _key: 'asc', - }, + }, + aggs: { + hostNames: { + terms: { + field: HOST_NAME, + size: Math.min(size, MAX_SIZE), + order: { + _key: 'asc', }, }, }, diff --git a/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_services/index.ts b/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_services/index.ts index eb2383e7e23ff..d4fd0f86a7f0e 100644 --- a/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_services/index.ts +++ b/x-pack/solutions/observability/plugins/apm_data_access/server/services/get_host_services/index.ts @@ -13,7 +13,7 @@ import { METRICSET_NAME, SERVICE_NAME, } from '@kbn/apm-types/es_fields'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { TimeRangeMetadata } from '../../../common'; import { RollupInterval, @@ -72,44 +72,42 @@ export function createGetHostServices({ apmEventClient }: ApmDataAccessServicesP }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: [ - { - bool: { - should: [ - ...termQuery(METRICSET_NAME, 'app'), - { - bool: { - must: [...termQuery(METRICSET_NAME, 'transaction')], - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: [ + { + bool: { + should: [ + ...termQuery(METRICSET_NAME, 'app'), + { + bool: { + must: [...termQuery(METRICSET_NAME, 'transaction')], }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - ...commonFiltersList, - ], - }, - }, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size, }, - aggs: { - latestAgent: { - top_metrics: { - metrics: [{ field: AGENT_NAME }], - sort: { - '@timestamp': 'desc', - }, - size: 1, + ...commonFiltersList, + ], + }, + }, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size, + }, + aggs: { + latestAgent: { + top_metrics: { + metrics: [{ field: AGENT_NAME }], + sort: { + '@timestamp': 'desc', }, + size: 1, }, }, }, @@ -127,29 +125,27 @@ export function createGetHostServices({ apmEventClient }: ApmDataAccessServicesP }, ], }, - body: { - track_total_hits: false, - size: 0, - query: { - bool: { - filter: commonFiltersList, - }, + track_total_hits: false, + size: 0, + query: { + bool: { + filter: commonFiltersList, }, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size, - }, - aggs: { - latestAgent: { - top_metrics: { - metrics: [{ field: AGENT_NAME }], - sort: { - '@timestamp': 'desc', - }, - size: 1, + }, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size, + }, + aggs: { + latestAgent: { + top_metrics: { + metrics: [{ field: AGENT_NAME }], + sort: { + '@timestamp': 'desc', }, + size: 1, }, }, }, diff --git a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/use_filter_values.ts b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/use_filter_values.ts index e7d70b742a727..7c7aa8cebe729 100644 --- a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/use_filter_values.ts +++ b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/use_filter_values.ts @@ -5,7 +5,7 @@ * 2.0. */ import { ExistsFilter, isExistsFilter } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ESFilter } from '@kbn/es-types'; import { PersistableFilter } from '@kbn/lens-plugin/common'; import { useValuesList } from '@kbn/observability-shared-plugin/public'; diff --git a/x-pack/solutions/observability/plugins/infra/common/alerting/logs/log_threshold/query_helpers.ts b/x-pack/solutions/observability/plugins/infra/common/alerting/logs/log_threshold/query_helpers.ts index 2af0c94ccbb41..d2dd67904aead 100644 --- a/x-pack/solutions/observability/plugins/infra/common/alerting/logs/log_threshold/query_helpers.ts +++ b/x-pack/solutions/observability/plugins/infra/common/alerting/logs/log_threshold/query_helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { type LogThresholdParams } from '@kbn/response-ops-rule-params/log_threshold'; import type { CountCriteria, Criterion, ExecutionTimeRange } from '.'; import { Comparator } from '.'; diff --git a/x-pack/solutions/observability/plugins/infra/common/search_strategies/log_entries/log_entries.ts b/x-pack/solutions/observability/plugins/infra/common/search_strategies/log_entries/log_entries.ts index c6b53abee7143..6100adf99c56f 100644 --- a/x-pack/solutions/observability/plugins/infra/common/search_strategies/log_entries/log_entries.ts +++ b/x-pack/solutions/observability/plugins/infra/common/search_strategies/log_entries/log_entries.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { logEntryAfterCursorRT, logEntryBeforeCursorRT, diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts index b7fa86cebfe37..b6d7f97c1d7c2 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { HttpHandler } from '@kbn/core/public'; import { decodeOrThrow } from '@kbn/io-ts-utils'; import { diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts index d7797e1d11a8f..42e0f0522453a 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts @@ -6,7 +6,7 @@ */ import type { HttpHandler } from '@kbn/core/public'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { decodeOrThrow } from '@kbn/io-ts-utils'; import type { ValidationIndicesFieldSpecification } from '../../../../../common/http_api'; diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts index 506e16f418fcf..b0a07807d51e5 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts @@ -6,7 +6,7 @@ */ import type { HttpHandler } from '@kbn/core/public'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IdFormat, JobType } from '../../../../common/http_api/latest'; import type { ValidateLogEntryDatasetsResponsePayload, diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts index 09dc53d65e487..1d4b6796a8cf7 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import type { HttpHandler } from '@kbn/core/public'; import type { IdFormat } from '../../../../../../common/http_api/latest'; diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx index 901bda6b068d4..6a4d491a4a7df 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx @@ -6,7 +6,7 @@ */ import createContainer from 'constate'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useMemo } from 'react'; import type { IdFormat } from '../../../../../../common/http_api/latest'; import { useLogAnalysisModule } from '../../log_analysis_module'; diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts index 84710dfa292b1..fe4989a04ed72 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts @@ -6,7 +6,7 @@ */ import { i18n } from '@kbn/i18n'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { HttpHandler } from '@kbn/core/public'; import type { IdFormat } from '../../../../../../common/http_api/latest'; import type { DatasetFilter, LogEntryRateJobType } from '../../../../../../common/log_analysis'; diff --git a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx index a867491eeadad..ae0d42597a416 100644 --- a/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx +++ b/x-pack/solutions/observability/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import createContainer from 'constate'; import { useMemo } from 'react'; import type { IdFormat } from '../../../../../../common/http_api/latest'; diff --git a/x-pack/solutions/observability/plugins/infra/public/utils/logs_overview_fetchers.ts b/x-pack/solutions/observability/plugins/infra/public/utils/logs_overview_fetchers.ts index 70fd808c4f810..ca8ce21bae823 100644 --- a/x-pack/solutions/observability/plugins/infra/public/utils/logs_overview_fetchers.ts +++ b/x-pack/solutions/observability/plugins/infra/public/utils/logs_overview_fetchers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { FetchData, FetchDataParams, diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/adapter_types.ts b/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/adapter_types.ts index 1d102a36209db..820744aa5683b 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/adapter_types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Lifecycle } from '@hapi/hapi'; import type { SharePluginSetup } from '@kbn/share-plugin/server'; import type { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server'; diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts index e8256e7a775a5..a5828d5085490 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportRequestParams } from '@elastic/elasticsearch'; import type { ElasticsearchClient, @@ -127,7 +127,7 @@ export class KibanaFramework { callWithRequest( requestContext: InfraPluginRequestHandlerContext, endpoint: 'search', - options?: CallWithRequestParams, + options?: CallWithRequestParams | estypes.SearchRequest, request?: KibanaRequest ): Promise>; callWithRequest( @@ -215,7 +215,7 @@ export class KibanaFramework { { ...params, ...frozenIndicesParams, - } as estypes.MsearchRequest, + } as estypes.SearchRequest, { signal } ), }); diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts b/x-pack/solutions/observability/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts index 6478dbe431a1b..084cc0223ba49 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts @@ -18,12 +18,10 @@ export const checkValidNode = async ( ignore_unavailable: true, index: indexPattern, terminate_after: 1, - body: { - size: 0, - query: { - match: { - [field]: id, - }, + size: 0, + query: { + match: { + [field]: id, }, }, }; diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/create_request.ts b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/create_request.ts index 4b93dbf3a6c04..16ebff0c4c9a2 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/create_request.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/create_request.ts @@ -99,18 +99,16 @@ export const createRequest = ( allow_no_indices: true, ignore_unavailable: true, index, - body: { - size: 0, - query: { bool: { filter: filters } }, - aggs: { - nodes: { - composite, - aggs: { - ...metricAggregations, - ...bucketSelector, - ...additionalContextAgg, - ...containerContextAgg, - }, + size: 0, + query: { bool: { filter: filters } }, + aggs: { + nodes: { + composite, + aggs: { + ...metricAggregations, + ...bucketSelector, + ...additionalContextAgg, + ...containerContextAgg, }, }, }, diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts index 98e86ea390d87..9e10c92b8f80a 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts @@ -19,7 +19,7 @@ import type { GroupedSearchQueryResponse, } from '../../../../common/alerting/logs/log_threshold'; import { Comparator } from '../../../../common/alerting/logs/log_threshold'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { positiveComparators, negativeComparators, @@ -274,60 +274,58 @@ describe('Log threshold executor', () => { index: 'filebeat-*', allow_no_indices: true, ignore_unavailable: true, - body: { - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: expect.any(Number), - lte: expect.any(Number), - format: 'epoch_millis', - }, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: expect.any(Number), + lte: expect.any(Number), + format: 'epoch_millis', }, }, - ...expectedPositiveFilterClauses, - ], - must_not: [...expectedNegativeFilterClauses], - }, + }, + ...expectedPositiveFilterClauses, + ], + must_not: [...expectedNegativeFilterClauses], }, - aggregations: { - groups: { - aggregations: { - additionalContext: { - top_hits: { - _source: false, - fields: ['host.*'], - size: 1, - }, + }, + aggregations: { + groups: { + aggregations: { + additionalContext: { + top_hits: { + _source: false, + fields: ['host.*'], + size: 1, }, }, - composite: { - size: 2000, - sources: [ - { - 'group-0-host.name': { - terms: { - field: 'host.name', - }, + }, + composite: { + size: 2000, + sources: [ + { + 'group-0-host.name': { + terms: { + field: 'host.name', }, }, - ], - }, + }, + ], }, }, - runtime_mappings: { - runtime_field: { - type: 'keyword', - script: { - lang: 'painless', - source: 'emit("a runtime value")', - }, + }, + runtime_mappings: { + runtime_field: { + type: 'keyword', + script: { + lang: 'painless', + source: 'emit("a runtime value")', }, }, - size: 0, }, + size: 0, }); }); @@ -354,79 +352,77 @@ describe('Log threshold executor', () => { index: 'filebeat-*', allow_no_indices: true, ignore_unavailable: true, - body: { - query: { - bool: { - filter: [ + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: expect.any(Number), + lte: expect.any(Number), + format: 'epoch_millis', + }, + }, + }, + ], + }, + }, + aggregations: { + groups: { + composite: { + size: 2000, + sources: [ { - range: { - '@timestamp': { - gte: expect.any(Number), - lte: expect.any(Number), - format: 'epoch_millis', + 'group-0-host.name': { + terms: { + field: 'host.name', }, }, }, ], }, - }, - aggregations: { - groups: { - composite: { - size: 2000, - sources: [ - { - 'group-0-host.name': { - terms: { - field: 'host.name', - }, - }, - }, - ], - }, - aggregations: { - filtered_results: { - filter: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: expect.any(Number), - lte: expect.any(Number), - format: 'epoch_millis', - }, + aggregations: { + filtered_results: { + filter: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: expect.any(Number), + lte: expect.any(Number), + format: 'epoch_millis', }, }, - ...expectedPositiveFilterClauses, - ], - must_not: [...expectedNegativeFilterClauses], - }, - }, - aggregations: { - additionalContext: { - top_hits: { - _source: false, - fields: ['host.*'], - size: 1, }, + ...expectedPositiveFilterClauses, + ], + must_not: [...expectedNegativeFilterClauses], + }, + }, + aggregations: { + additionalContext: { + top_hits: { + _source: false, + fields: ['host.*'], + size: 1, }, }, }, }, }, }, - runtime_mappings: { - runtime_field: { - type: 'keyword', - script: { - lang: 'painless', - source: 'emit("a runtime value")', - }, + }, + runtime_mappings: { + runtime_field: { + type: 'keyword', + script: { + lang: 'painless', + source: 'emit("a runtime value")', }, }, - size: 0, }, + size: 0, }); }); }); diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts index e9da772aa1f14..81bf6226bed2b 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { getAlertDetailsUrl } from '@kbn/observability-plugin/common'; import { @@ -748,7 +748,7 @@ export const getGroupedESQuery = ( }, }; - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { query: { bool: { filter: [rangeFilter, ...mustFilters], @@ -764,7 +764,7 @@ export const getGroupedESQuery = ( index, allow_no_indices: true, ignore_unavailable: true, - body, + ...body, }; } else { const aggregations = { @@ -794,7 +794,7 @@ export const getGroupedESQuery = ( }, }; - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { query: { bool: { filter: [groupedRangeFilter], @@ -809,7 +809,7 @@ export const getGroupedESQuery = ( index, allow_no_indices: true, ignore_unavailable: true, - body, + ...body, }; } }; @@ -827,7 +827,7 @@ export const getUngroupedESQuery = ( executionTimeRange ); - const body: estypes.SearchRequest['body'] = { + const body: estypes.SearchRequest = { // Ensure we accurately track the hit count for the ungrouped case, otherwise we can only ensure accuracy up to 10,000. track_total_hits: true, query: { @@ -861,7 +861,7 @@ const getGroupedResults = async (query: object, esClient: ElasticsearchClient) = while (true) { const queryWithAfterKey: any = { ...query }; - queryWithAfterKey.body.aggregations.groups.composite.after = lastAfterKey; + queryWithAfterKey.aggregations.groups.composite.after = lastAfterKey; const groupResponse: GroupedSearchQueryResponse = decodeOrThrow(GroupedSearchQueryResponseRT)( await esClient.search(queryWithAfterKey) ); diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/metric_threshold/lib/get_data.ts b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/metric_threshold/lib/get_data.ts index aebb064067bf6..ea46365c2830e 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/alerting/metric_threshold/lib/get_data.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/alerting/metric_threshold/lib/get_data.ts @@ -266,7 +266,7 @@ export const getData = async ( index, allow_no_indices: true, ignore_unavailable: true, - body: getElasticsearchMetricQuery( + ...getElasticsearchMetricQuery( params, timeframe, compositeSize, diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_alerts_client.ts b/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_alerts_client.ts index 581ef994ea1a6..3af38abaca5f5 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_alerts_client.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_alerts_client.ts @@ -5,16 +5,19 @@ * 2.0. */ import { isEmpty } from 'lodash'; -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { InferSearchResponseOf } from '@kbn/es-types'; import type { ParsedTechnicalFields } from '@kbn/rule-registry-plugin/common'; import type { KibanaRequest } from '@kbn/core/server'; import { OBSERVABILITY_RULE_TYPE_IDS } from '@kbn/rule-data-utils'; +import type { estypes } from '@elastic/elasticsearch'; import type { InfraBackendLibs } from '../infra_types'; type RequiredParams = ESSearchRequest & { size: number; track_total_hits: boolean | number; + sort?: estypes.SortOptions[]; + _source?: string[] | false; }; export type InfraAlertsClient = Awaited>; diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.test.ts b/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.test.ts index 144cd7f274aa0..024f831061dbb 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.test.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.test.ts @@ -41,22 +41,18 @@ const infraMetricsTestHarness = }); await client.search({ - body: { - query: input, - size: 1, - track_total_hits: false, - }, + query: input, + size: 1, + track_total_hits: false, }); expect(callWithRequest).toBeCalledWith( context, 'search', { - body: { - query: output, - size: 1, - track_total_hits: false, - }, + query: output, + size: 1, + track_total_hits: false, ignore_unavailable: true, index: ['*.indices'], }, diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.ts b/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.ts index faba18b6d745d..aeaadbfe08ed5 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/helpers/get_infra_metrics_client.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import type { InferSearchResponseOf } from '@kbn/es-types'; import type { KibanaRequest } from '@kbn/core/server'; import { searchExcludedDataTiers } from '@kbn/observability-plugin/common/ui_settings_keys'; @@ -15,10 +15,8 @@ import type { InfraPluginRequestHandlerContext } from '../../types'; import type { InfraBackendLibs } from '../infra_types'; type RequiredParams = Omit & { - body: { - size: number; - track_total_hits: boolean | number; - }; + size: number; + track_total_hits: boolean | number; }; export type InfraMetricsClient = Awaited>; @@ -47,7 +45,7 @@ export async function getInfraMetricsClient({ search( searchParams: TParams ): Promise> { - const searchFilter = searchParams.body.query?.bool?.must_not ?? []; + const searchFilter = searchParams.query?.bool?.must_not ?? []; // This flattens arrays by one level, and non-array values can be added as well, so it all // results in a nice [QueryDsl, QueryDsl, ...] array. @@ -60,14 +58,11 @@ export async function getInfraMetricsClient({ ...searchParams, ignore_unavailable: true, index: metricsIndices, - body: { - ...searchParams.body, - query: { - ...searchParams.body.query, - bool: { - ...searchParams.body.query?.bool, - must_not: mustNot, - }, + query: { + ...searchParams.query, + bool: { + ...searchParams.query?.bool, + must_not: mustNot, }, }, }, diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts index c61bcf78b4995..36d76baa6c1d5 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { PersistedLogViewReference, ResolvedLogView } from '@kbn/logs-shared-plugin/common'; import { decodeOrThrow } from '@kbn/io-ts-utils'; import type { IdFormat, IdFormatByJobType } from '../../../common/http_api/latest'; diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts index 77bdf25693946..93caed66a0ef9 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { LogEntryContext, diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts index 22430310c2aad..6f89134e360af 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import * as rt from 'io-ts'; import { commonSearchSuccessResponseFieldsRT } from '../../../utils/elasticsearch_runtime_types'; import { defaultRequestParameters } from './common'; @@ -21,36 +21,34 @@ export const createLogEntryCategoryExamplesQuery = ( exampleCount: number ): estypes.SearchRequest => ({ ...defaultRequestParameters, - body: { - size: exampleCount, - query: { - bool: { - filter: [ - { - range: { - [timestampField]: { - gte: startTime, - lte: endTime, - format: 'epoch_millis', - }, + size: exampleCount, + query: { + bool: { + filter: [ + { + range: { + [timestampField]: { + gte: startTime, + lte: endTime, + format: 'epoch_millis', }, }, - { - match: { - message: { - query: categoryQuery, - operator: 'and', - }, + }, + { + match: { + message: { + query: categoryQuery, + operator: 'and', }, }, - ], - }, + }, + ], }, - runtime_mappings: runtimeMappings, - sort: [{ [timestampField]: 'asc' }, { [tiebreakerField]: 'asc' }], - _source: false, - fields: ['event.dataset', 'message', 'container.id', 'host.name', 'log.file.path'], }, + runtime_mappings: runtimeMappings, + sort: [{ [timestampField]: 'asc' }, { [tiebreakerField]: 'asc' }], + _source: false, + fields: ['event.dataset', 'message', 'container.id', 'host.name', 'log.file.path'], index: indices, }); diff --git a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts index 4076e7c3e1ef9..b9b5916fabcea 100644 --- a/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts +++ b/x-pack/solutions/observability/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import * as rt from 'io-ts'; import { partitionField } from '../../../../common/log_analysis'; import { commonSearchSuccessResponseFieldsRT } from '../../../utils/elasticsearch_runtime_types'; @@ -23,61 +23,59 @@ export const createLogEntryExamplesQuery = ( categoryQuery?: string ): estypes.SearchRequest => ({ ...defaultRequestParameters, - body: { - size: exampleCount, - query: { - bool: { - filter: [ - { - range: { - [timestampField]: { - gte: startTime, - lte: endTime, - format: 'epoch_millis', - }, + size: exampleCount, + query: { + bool: { + filter: [ + { + range: { + [timestampField]: { + gte: startTime, + lte: endTime, + format: 'epoch_millis', }, }, - ...(dataset !== '' - ? [ - { - term: { - [partitionField]: dataset, - }, + }, + ...(dataset !== '' + ? [ + { + term: { + [partitionField]: dataset, }, - ] - : [ - { - bool: { - must_not: [ - { - exists: { - field: partitionField, - }, + }, + ] + : [ + { + bool: { + must_not: [ + { + exists: { + field: partitionField, }, - ], - }, - }, - ]), - ...(categoryQuery - ? [ - { - match: { - message: { - query: categoryQuery, - operator: 'and' as const, }, + ], + }, + }, + ]), + ...(categoryQuery + ? [ + { + match: { + message: { + query: categoryQuery, + operator: 'and' as const, }, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, - runtime_mappings: runtimeMappings, - sort: [{ [timestampField]: 'asc' }, { [tiebreakerField]: 'asc' }], - _source: false, - fields: ['event.dataset', 'message'], }, + runtime_mappings: runtimeMappings, + sort: [{ [timestampField]: 'asc' }, { [tiebreakerField]: 'asc' }], + _source: false, + fields: ['event.dataset', 'message'], index: indices, }); diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/entities/get_has_metrics_data.ts b/x-pack/solutions/observability/plugins/infra/server/routes/entities/get_has_metrics_data.ts index 41f76f5d1aa22..4b66ab08cb2ed 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/entities/get_has_metrics_data.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/entities/get_has_metrics_data.ts @@ -20,12 +20,10 @@ export async function getHasMetricsData({ const results = await infraMetricsClient.search({ allow_no_indices: true, ignore_unavailable: true, - body: { - track_total_hits: true, - terminate_after: 1, - size: 0, - query: { bool: { filter: termQuery(field, entityId) } }, - }, + track_total_hits: true, + terminate_after: 1, + size: 0, + query: { bool: { filter: termQuery(field, entityId) } }, }); return results.hits.total.value !== 0; } diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_all_hosts.ts b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_all_hosts.ts index abeb51140d189..d3a47c55bd634 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_all_hosts.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_all_hosts.ts @@ -49,58 +49,56 @@ export const getAllHosts = async ({ const response = await infraMetricsClient.search({ allow_no_indices: true, ignore_unavailable: true, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [...termsQuery(HOST_NAME_FIELD, ...hostNames), ...rangeQuery(from, to)], - should: [...documentsFilter], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [...termsQuery(HOST_NAME_FIELD, ...hostNames), ...rangeQuery(from, to)], + should: [...documentsFilter], }, - aggs: { - // find hosts with metrics that are monitored by the system integration. - monitoredHosts: { - filter: getFilterByIntegration('system'), - aggs: { - names: { - terms: { - field: HOST_NAME_FIELD, - size: limit, - order: { - _key: 'asc', - }, + }, + aggs: { + // find hosts with metrics that are monitored by the system integration. + monitoredHosts: { + filter: getFilterByIntegration('system'), + aggs: { + names: { + terms: { + field: HOST_NAME_FIELD, + size: limit, + order: { + _key: 'asc', }, }, }, }, - allHostMetrics: { - terms: { - field: HOST_NAME_FIELD, - size: limit, - order: { - _key: 'asc', - }, + }, + allHostMetrics: { + terms: { + field: HOST_NAME_FIELD, + size: limit, + order: { + _key: 'asc', }, - aggs: { - ...metricAggregations, - [METADATA_AGGREGATION_NAME]: { - top_metrics: { - metrics: [ - { - field: 'host.os.name', - }, - { - field: 'cloud.provider', - }, - { - field: 'host.ip', - }, - ], - size: 1, - sort: { - '@timestamp': 'desc', + }, + aggs: { + ...metricAggregations, + [METADATA_AGGREGATION_NAME]: { + top_metrics: { + metrics: [ + { + field: 'host.os.name', + }, + { + field: 'cloud.provider', + }, + { + field: 'host.ip', }, + ], + size: 1, + sort: { + '@timestamp': 'desc', }, }, }, diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_filtered_hosts.ts b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_filtered_hosts.ts index bbb10a0c70ea4..45937abfc2e4e 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_filtered_hosts.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_filtered_hosts.ts @@ -23,26 +23,24 @@ export const getFilteredHostNames = async ({ }) => { const response = await infraMetricsClient.search({ allow_no_indices: true, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [ - ...castArray(query), - ...rangeQuery(from, to), - getFilterByIntegration(SYSTEM_INTEGRATION), - ], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [ + ...castArray(query), + ...rangeQuery(from, to), + getFilterByIntegration(SYSTEM_INTEGRATION), + ], }, - aggs: { - uniqueHostNames: { - terms: { - field: HOST_NAME_FIELD, - size: limit, - order: { - _key: 'asc', - }, + }, + aggs: { + uniqueHostNames: { + terms: { + field: HOST_NAME_FIELD, + size: limit, + order: { + _key: 'asc', }, }, }, @@ -64,18 +62,16 @@ export const getHasDataFromSystemIntegration = async ({ const hitCount = await infraMetricsClient.search({ allow_no_indices: true, ignore_unavailable: true, - body: { - size: 0, - terminate_after: 1, - track_total_hits: true, - query: { - bool: { - filter: [ - ...castArray(query), - ...rangeQuery(from, to), - getFilterByIntegration(SYSTEM_INTEGRATION), - ], - }, + size: 0, + terminate_after: 1, + track_total_hits: true, + query: { + bool: { + filter: [ + ...castArray(query), + ...rangeQuery(from, to), + getFilterByIntegration(SYSTEM_INTEGRATION), + ], }, }, }); diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_alerts_count.ts b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_alerts_count.ts index 48e1328de56bb..112ddbe9e1239 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_alerts_count.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_alerts_count.ts @@ -53,7 +53,7 @@ export async function getHostsAlertsCount({ field: HOST_NAME_FIELD, size: limit, order: { - _key: 'asc', + _key: 'asc' as const, }, }, aggs: { diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_count.ts b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_count.ts index 8b08021187faa..367c7a9309322 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_count.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/host/get_hosts_count.ts @@ -33,20 +33,18 @@ export async function getHostsCount({ const response = await infraMetricsClient.search({ allow_no_indices: true, - body: { - size: 0, - track_total_hits: false, - query: { - bool: { - filter: [query, ...rangeQuery(from, to)], - should: [...documentsFilter], - }, + size: 0, + track_total_hits: false, + query: { + bool: { + filter: [query, ...rangeQuery(from, to)], + should: [...documentsFilter], }, - aggs: { - totalCount: { - cardinality: { - field: HOST_NAME_FIELD, - }, + }, + aggs: { + totalCount: { + cardinality: { + field: HOST_NAME_FIELD, }, }, }, diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/datasets.ts b/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/datasets.ts index 54ea70d46909e..e69cf5972ae3d 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/datasets.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/datasets.ts @@ -6,7 +6,7 @@ */ import Boom from '@hapi/boom'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { createRouteValidationFunction } from '@kbn/io-ts-utils'; import type { InfraBackendLibs } from '../../../lib/infra_types'; diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/indices.ts b/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/indices.ts index 39fcc918811f5..0b8a3dcfe40c3 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/indices.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/log_analysis/validation/indices.ts @@ -53,9 +53,7 @@ export const initValidateLogAnalysisIndicesRoute = ({ framework }: InfraBackendL fields: fields.map((field) => field.name), ignore_unavailable: true, index, - body: { - runtime_mappings: runtimeMappings, - }, + runtime_mappings: runtimeMappings, }); if (fieldCaps.indices.length === 0) { diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/metrics_sources/index.ts b/x-pack/solutions/observability/plugins/infra/server/routes/metrics_sources/index.ts index 4290db429aead..a448536314bae 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/metrics_sources/index.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/metrics_sources/index.ts @@ -225,24 +225,22 @@ export const initMetricsSourceConfigurationRoutes = (libs: InfraBackendLibs) => const results = await infraMetricsClient.search({ allow_no_indices: true, ignore_unavailable: true, - body: { - track_total_hits: true, - terminate_after: 1, - size: 0, - ...(modules.length > 0 - ? { - query: { - bool: { - should: [ - ...termsQuery(EVENT_MODULE, ...modules), - ...termsQuery(METRICSET_MODULE, ...modules), - ], - minimum_should_match: 1, - }, + track_total_hits: true, + terminate_after: 1, + size: 0, + ...(modules.length > 0 + ? { + query: { + bool: { + should: [ + ...termsQuery(EVENT_MODULE, ...modules), + ...termsQuery(METRICSET_MODULE, ...modules), + ], + minimum_should_match: 1, }, - } - : {}), - }, + }, + } + : {}), }); return response.ok({ diff --git a/x-pack/solutions/observability/plugins/infra/server/utils/calculate_metric_interval.ts b/x-pack/solutions/observability/plugins/infra/server/utils/calculate_metric_interval.ts index fbce4ecc117b2..7610749cd08e8 100644 --- a/x-pack/solutions/observability/plugins/infra/server/utils/calculate_metric_interval.ts +++ b/x-pack/solutions/observability/plugins/infra/server/utils/calculate_metric_interval.ts @@ -38,34 +38,32 @@ export const calculateMetricInterval = async ( allow_no_indices: true, index: options.indexPattern, ignore_unavailable: true, - body: { - query: { - bool: { - filter: [ - { - range: { - [TIMESTAMP_FIELD]: { - gte: from, - lte: options.timerange.to, - format: 'epoch_millis', - }, + query: { + bool: { + filter: [ + { + range: { + [TIMESTAMP_FIELD]: { + gte: from, + lte: options.timerange.to, + format: 'epoch_millis', }, }, - ], - }, - }, - size: 0, - aggs: { - modules: { - terms: { - field: 'event.dataset', - include: modules, }, - aggs: { - period: { - max: { - field: 'metricset.period', - }, + ], + }, + }, + size: 0, + aggs: { + modules: { + terms: { + field: 'event.dataset', + include: modules, + }, + aggs: { + period: { + max: { + field: 'metricset.period', }, }, }, diff --git a/x-pack/solutions/observability/plugins/inventory/server/lib/create_alerts_client/create_alerts_client.ts b/x-pack/solutions/observability/plugins/inventory/server/lib/create_alerts_client/create_alerts_client.ts index 06e43526e58f1..28d16b0598961 100644 --- a/x-pack/solutions/observability/plugins/inventory/server/lib/create_alerts_client/create_alerts_client.ts +++ b/x-pack/solutions/observability/plugins/inventory/server/lib/create_alerts_client/create_alerts_client.ts @@ -6,8 +6,8 @@ */ import { isEmpty } from 'lodash'; -import type { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { InferSearchResponseOf } from '@kbn/es-types'; +import type { SortOptions } from '@elastic/elasticsearch/lib/api/types'; +import type { ESSearchRequest, InferSearchResponseOf } from '@kbn/es-types'; import type { ParsedTechnicalFields } from '@kbn/rule-registry-plugin/common'; import { OBSERVABILITY_RULE_TYPE_IDS } from '@kbn/rule-data-utils'; import type { InventoryRouteHandlerResources } from '../../routes/types'; @@ -26,6 +26,8 @@ export async function createAlertsClient({ throw Error('No alert indices exist'); } type RequiredParams = ESSearchRequest & { + _source?: string[] | false; + sort?: SortOptions[]; size: number; track_total_hits: boolean | number; }; diff --git a/x-pack/solutions/observability/plugins/inventory/server/routes/entities/get_group_by_terms_agg.ts b/x-pack/solutions/observability/plugins/inventory/server/routes/entities/get_group_by_terms_agg.ts index 705c9ea43a642..d1bca45ad884d 100644 --- a/x-pack/solutions/observability/plugins/inventory/server/routes/entities/get_group_by_terms_agg.ts +++ b/x-pack/solutions/observability/plugins/inventory/server/routes/entities/get_group_by_terms_agg.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { AggregationsCompositeAggregation } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsCompositeAggregation } from '@elastic/elasticsearch/lib/api/types'; export const getGroupByTermsAgg = (fields: { [key: string]: string[] }, maxSize = 500) => { return Object.entries(fields).reduce((acc, [sourceId, identityFields]) => { diff --git a/x-pack/solutions/observability/plugins/investigate_app/server/clients/create_entities_es_client.ts b/x-pack/solutions/observability/plugins/investigate_app/server/clients/create_entities_es_client.ts index 6eb1beaf0ede6..12a14883ec84d 100644 --- a/x-pack/solutions/observability/plugins/investigate_app/server/clients/create_entities_es_client.ts +++ b/x-pack/solutions/observability/plugins/investigate_app/server/clients/create_entities_es_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import { InferSearchResponseOf } from '@kbn/es-types'; import type { KibanaRequest } from '@kbn/core/server'; import { ElasticsearchClient } from '@kbn/core/server'; @@ -98,14 +98,13 @@ export function createEntitiesESClient({ ): Promise<{ responses: Array> }> { const searches = allSearches .map((params) => { + const { index, ...body } = params; const searchParams: [MsearchMultisearchHeader, MsearchMultisearchBody] = [ { - index: [params.index], + index: [index], ignore_unavailable: true, }, - { - ...params.body, - }, + body, ]; return searchParams; diff --git a/x-pack/solutions/observability/plugins/investigate_app/server/lib/get_sample_documents.ts b/x-pack/solutions/observability/plugins/investigate_app/server/lib/get_sample_documents.ts index 966bda5fc6169..6a6474949c1ab 100644 --- a/x-pack/solutions/observability/plugins/investigate_app/server/lib/get_sample_documents.ts +++ b/x-pack/solutions/observability/plugins/investigate_app/server/lib/get_sample_documents.ts @@ -5,7 +5,7 @@ * 2.0. */ import pLimit from 'p-limit'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { castArray, sortBy, uniq, partition, shuffle } from 'lodash'; import { truncateList } from '@kbn/inference-common'; import { QueryDslQueryContainer } from '@kbn/data-views-plugin/common/types'; @@ -47,31 +47,29 @@ export async function getSampleDocuments({ index: indexPatterns, track_total_hits: true, size: count, - body: { - query: { - bool: { - should: [ - { - function_score: { - functions: [ - { - random_score: {}, - }, - ], - }, + query: { + bool: { + should: [ + { + function_score: { + functions: [ + { + random_score: {}, + }, + ], }, - ], - must: [...rangeQuery(start, end), ...(dslFilter ?? [])], - }, + }, + ], + must: [...rangeQuery(start, end), ...(dslFilter ?? [])], }, - sort: { - _score: { - order: 'desc', - }, + }, + sort: { + _score: { + order: 'desc', }, - _source: false, - fields: ['*' as const], }, + _source: false, + fields: ['*' as const], }) .then((response) => { const hits = response.hits.total as estypes.SearchTotalHits; diff --git a/x-pack/solutions/observability/plugins/investigate_app/server/lib/queries/index.ts b/x-pack/solutions/observability/plugins/investigate_app/server/lib/queries/index.ts index 2dff4d40ec850..2beaf66c59dac 100644 --- a/x-pack/solutions/observability/plugins/investigate_app/server/lib/queries/index.ts +++ b/x-pack/solutions/observability/plugins/investigate_app/server/lib/queries/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; export function rangeQuery( start: number, diff --git a/x-pack/solutions/observability/plugins/investigate_app/server/services/get_alerts_client.ts b/x-pack/solutions/observability/plugins/investigate_app/server/services/get_alerts_client.ts index eae37e54c5648..4d8fe46e4206b 100644 --- a/x-pack/solutions/observability/plugins/investigate_app/server/services/get_alerts_client.ts +++ b/x-pack/solutions/observability/plugins/investigate_app/server/services/get_alerts_client.ts @@ -6,10 +6,11 @@ */ import { isEmpty } from 'lodash'; -import { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchRequest as ESSearchRequest } from '@elastic/elasticsearch/lib/api/types'; import { InferSearchResponseOf } from '@kbn/es-types'; import { ParsedTechnicalFields } from '@kbn/rule-registry-plugin/common'; import { OBSERVABILITY_RULE_TYPE_IDS } from '@kbn/rule-data-utils'; +import type { estypes } from '@elastic/elasticsearch'; import { InvestigateAppRouteHandlerResources } from '../routes/types'; export type AlertsClient = Awaited>; @@ -29,6 +30,8 @@ export async function getAlertsClient({ type RequiredParams = ESSearchRequest & { size: number; track_total_hits: boolean | number; + sort?: estypes.SortOptions[]; + _source?: string[] | false; }; return { diff --git a/x-pack/solutions/observability/plugins/investigate_app/server/services/get_entities.ts b/x-pack/solutions/observability/plugins/investigate_app/server/services/get_entities.ts index 0aa5d674702e3..9555aafc663f8 100644 --- a/x-pack/solutions/observability/plugins/investigate_app/server/services/get_entities.ts +++ b/x-pack/solutions/observability/plugins/investigate_app/server/services/get_entities.ts @@ -12,8 +12,8 @@ import type { EntityWithSource, EntitySource, } from '@kbn/investigation-shared'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { IndicesIndexState } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; +import type { IndicesIndexState } from '@elastic/elasticsearch/lib/api/types'; import type { EntitiesESClient } from '../clients/create_entities_es_client'; import { SERVICE_ENTITIES_LATEST_ALIAS, @@ -156,12 +156,10 @@ const getFetchEntityPromise = ({ return shouldFetch ? entitiesEsClient .search<{ source_index: string[]; entity: EntitiesLatest['entity'] }>(index, { - body: { - query: { - bool: { - should: shouldMatch, - minimum_should_match: 1, - }, + query: { + bool: { + should: shouldMatch, + minimum_should_match: 1, }, }, }) diff --git a/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/hooks/metrics_to_api_options.ts b/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/hooks/metrics_to_api_options.ts index 61c842a4fecf4..76cf25829bb60 100644 --- a/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/hooks/metrics_to_api_options.ts +++ b/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/hooks/metrics_to_api_options.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ObjectValues } from '../../../../../common/utility_types'; import type { MetricsExplorerOptions, @@ -21,7 +21,7 @@ The metrics_explorer endpoint expects a list of the metrics to use, like this: { field: 'some.other.metric.field', aggregation: 'min' }, ] -The API then responds with a series, which is a list of rows (buckets from a date_histogram +The API then responds with a series, which is a list of rows (buckets from a date_histogram aggregation), where each bucket has this format: { metric_0: 99, metric_1: 88 } @@ -29,9 +29,9 @@ For each metric in the request, a key like metric_X is defined, and the number u which the metric appeared in the request. So if the metric for 'some.metric.field' is first, it'll be mapped to metric_0, but if the code changes and it is now second, it will be mapped to metric_1. -This makes the code that consumes the API response fragile to such re-ordering, the types and +This makes the code that consumes the API response fragile to such re-ordering, the types and functions in this file are used to reduce this fragility and allowing consuming code to reference -the metrics by their field names instead. +the metrics by their field names instead. The returned metricByField object, handles the translation from field name to "index name". For example, in the transform function passed to useInfrastructureNodeMetrics it can be used to find a field metric like this: diff --git a/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/types.ts b/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/types.ts index 21023f0b3a71b..c4bb98034159a 100644 --- a/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/types.ts +++ b/x-pack/solutions/observability/plugins/metrics_data_access/public/components/infrastructure_node_metrics_tables/shared/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { CoreProvidersProps } from '../../../apps/common_providers'; import type { MetricsDataClient } from '../../../lib/metrics_client'; diff --git a/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/adapter_types.ts b/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/adapter_types.ts index e5631a5d83e39..90c610947dfea 100644 --- a/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/adapter_types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Lifecycle } from '@hapi/hapi'; import type { SharePluginSetup } from '@kbn/share-plugin/server'; import type { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server'; diff --git a/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/kibana_framework_adapter.ts index 799373c78d132..e05695a0a4ed0 100644 --- a/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/solutions/observability/plugins/metrics_data_access/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportRequestParams } from '@elastic/elasticsearch'; import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; import type { @@ -170,7 +170,7 @@ export class KibanaFramework { apiResult = elasticsearch.client.asCurrentUser.search({ ...params, ...frozenIndicesParams, - }); + } as estypes.SearchRequest); break; case 'msearch': apiResult = elasticsearch.client.asCurrentUser.msearch({ diff --git a/x-pack/solutions/observability/plugins/observability/public/hooks/use_fetch_alert_data.ts b/x-pack/solutions/observability/plugins/observability/public/hooks/use_fetch_alert_data.ts index b9254a979a53c..d297b9d291301 100644 --- a/x-pack/solutions/observability/plugins/observability/public/hooks/use_fetch_alert_data.ts +++ b/x-pack/solutions/observability/plugins/observability/public/hooks/use_fetch_alert_data.ts @@ -8,7 +8,7 @@ import { useCallback, useMemo } from 'react'; import { isEmpty } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { HttpSetup } from '@kbn/core/public'; import { BASE_RAC_ALERTS_API_PATH } from '@kbn/rule-registry-plugin/common/constants'; import { useDataFetcher } from './use_data_fetcher'; diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/annotations/create_annotations_client.ts b/x-pack/solutions/observability/plugins/observability/server/lib/annotations/create_annotations_client.ts index 5bd7395c3ca71..26153dce46f06 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/annotations/create_annotations_client.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/annotations/create_annotations_client.ts @@ -305,11 +305,9 @@ export function createAnnotationsClient(params: { return await esClient.deleteByQuery({ index: readIndex, ignore_unavailable: true, - body: { - query: { - term: { - _id: id, - }, + query: { + term: { + _id: id, }, }, refresh: true, diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/annotations/permissions.ts b/x-pack/solutions/observability/plugins/observability/server/lib/annotations/permissions.ts index 188d0a0f39442..861fb714d9d35 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/annotations/permissions.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/annotations/permissions.ts @@ -16,13 +16,11 @@ export const checkAnnotationsPermissions = async ({ esClient: ElasticsearchClient; }) => { return esClient.security.hasPrivileges({ - body: { - index: [ - { - names: [index], - privileges: ['read', 'write'] as SecurityIndexPrivilege[], - }, - ], - }, + index: [ + { + names: [index], + privileges: ['read', 'write'] as SecurityIndexPrivilege[], + }, + ], }); }; diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/check_missing_group.ts b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/check_missing_group.ts index 2d8952a98fa78..7713dee4e8c06 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/check_missing_group.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/check_missing_group.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { EsQueryConfig } from '@kbn/es-query'; diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/evaluate_rule.ts b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/evaluate_rule.ts index e0d861f53ae38..926e01c2ca33b 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/evaluate_rule.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/evaluate_rule.ts @@ -6,7 +6,7 @@ */ import moment from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import { EsQueryConfig } from '@kbn/es-query'; import type { Logger } from '@kbn/logging'; diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/get_data.ts b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/get_data.ts index 0f1aab36895e9..e4edad204ffd9 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/get_data.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/get_data.ts @@ -6,7 +6,7 @@ */ import type { SearchResponse, AggregationsAggregate } from '@elastic/elasticsearch/lib/api/types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { EsQueryConfig } from '@kbn/es-query'; import type { Logger } from '@kbn/logging'; @@ -204,7 +204,7 @@ export const getData = async ( index, allow_no_indices: true, ignore_unavailable: true, - body: getElasticsearchMetricQuery( + ...getElasticsearchMetricQuery( params, timeframe, timeFieldName, diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.ts b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.ts index 8cf6867aa4a01..e0be82fd43574 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.ts @@ -6,7 +6,7 @@ */ import moment from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { estypes } from '@elastic/elasticsearch'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { EsQueryConfig, Filter } from '@kbn/es-query'; import { diff --git a/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index.ts b/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index.ts index e2aadbaafd382..14c1381746dfc 100644 --- a/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index.ts +++ b/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index.ts @@ -4,12 +4,12 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import pRetry from 'p-retry'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; -export type Mappings = Required['body']['mappings'] & - Required['body']; +export type Mappings = Required['mappings'] & + Omit; export async function createOrUpdateIndex({ index, @@ -71,15 +71,13 @@ function createNewIndex({ }: { index: string; client: ElasticsearchClient; - mappings: Required['body']['mappings']; + mappings?: Required['mappings']; }) { return client.indices.create({ index, - body: { - // auto_expand_replicas: Allows cluster to not have replicas for this index - settings: { index: { auto_expand_replicas: '0-1' } }, - mappings, - }, + // auto_expand_replicas: Allows cluster to not have replicas for this index + settings: { index: { auto_expand_replicas: '0-1' } }, + mappings, }); } @@ -90,10 +88,11 @@ function updateExistingIndex({ }: { index: string; client: ElasticsearchClient; - mappings: estypes.IndicesPutMappingRequest['body']; + mappings?: Omit; }) { return client.indices.putMapping({ index, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 body: mappings, }); } diff --git a/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index_template.ts b/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index_template.ts index 4c747c71614ef..cebdbaec8d0e3 100644 --- a/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index_template.ts +++ b/x-pack/solutions/observability/plugins/observability/server/utils/create_or_update_index_template.ts @@ -6,7 +6,7 @@ */ import pRetry from 'p-retry'; import { Logger, ElasticsearchClient } from '@kbn/core/server'; -import { IndicesPutIndexTemplateRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { IndicesPutIndexTemplateRequest } from '@elastic/elasticsearch/lib/api/types'; export async function createOrUpdateIndexTemplate({ indexTemplate, @@ -29,7 +29,7 @@ export async function createOrUpdateIndexTemplate({ return await pRetry( async () => { logger.debug( - `Create index template: "${indexTemplate.name}" for index pattern "${indexTemplate.body?.index_patterns}"` + `Create index template: "${indexTemplate.name}" for index pattern "${indexTemplate.index_patterns}"` ); const result = await client.indices.putIndexTemplate(indexTemplate); diff --git a/x-pack/solutions/observability/plugins/observability/server/utils/queries.ts b/x-pack/solutions/observability/plugins/observability/server/utils/queries.ts index e66fca3264f1b..2d64bc8feaaf8 100644 --- a/x-pack/solutions/observability/plugins/observability/server/utils/queries.ts +++ b/x-pack/solutions/observability/plugins/observability/server/utils/queries.ts @@ -6,7 +6,7 @@ */ import { reject } from 'lodash'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { ESSearchResponse } from '@kbn/es-types'; import { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; diff --git a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/scripts/evaluation/evaluation.ts b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/scripts/evaluation/evaluation.ts index 9b20402952583..7e108c193ee49 100644 --- a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/scripts/evaluation/evaluation.ts +++ b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/scripts/evaluation/evaluation.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import { run } from '@kbn/dev-cli-runner'; import * as fastGlob from 'fast-glob'; import yargs from 'yargs'; @@ -42,6 +42,8 @@ function runEvaluations() { const kibanaClient = new KibanaClient(log, serviceUrls.kibanaUrl, argv.spaceId); const esClient = new Client({ node: serviceUrls.esUrl, + Connection: HttpConnection, + requestTimeout: 30_000, }); await kibanaClient.createSpaceIfNeeded(); diff --git a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts index 27c3fa288f5b0..0ab1ea82775e0 100644 --- a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts +++ b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts @@ -5,9 +5,13 @@ * 2.0. */ -import type { AggregationsAutoDateHistogramAggregation } from '@elastic/elasticsearch/lib/api/types'; +import type { + AggregationsAggregationContainer, + AggregationsAutoDateHistogramAggregation, +} from '@elastic/elasticsearch/lib/api/types'; import type { QueryDslQueryContainer } from '@kbn/data-views-plugin/common/types'; import type { ChangePointType } from '@kbn/es-types/src'; +import type { AggregateOf } from '@kbn/es-types/src/search'; import type { ObservabilityAIAssistantElasticsearchClient } from '../../clients/elasticsearch'; export async function getLogChanges({ @@ -68,7 +72,8 @@ export async function getLogChanges({ change_point: { buckets_path: 'over_time>_count', }, - }, + // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 + } as AggregationsAggregationContainer, }, }, }, @@ -78,6 +83,11 @@ export async function getLogChanges({ return ( response.aggregations?.sampler.groups.buckets.map((group) => { + const changes = group.changes as AggregateOf< + { change_point: { buckets_path: string } }, + unknown + >; + return { key: group.key, pattern: group.regex, @@ -86,12 +96,12 @@ export async function getLogChanges({ y: bucket.doc_count, })), changes: - group.changes.type.indeterminable || !group.changes.bucket?.key + changes.type.indeterminable || !changes.bucket?.key ? { type: 'indeterminable' as ChangePointType } : { - time: new Date(group.changes.bucket.key).toISOString(), - type: Object.keys(group.changes.type)[0] as keyof typeof group.changes.type, - ...Object.values(group.changes.type)[0], + time: new Date(changes.bucket.key).toISOString(), + type: Object.keys(changes.type)[0] as keyof typeof changes.type, + ...Object.values(changes.type)[0], }, }; }) ?? [] diff --git a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts index b7a5d53727a97..8362d7fb1e9fc 100644 --- a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts +++ b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts @@ -4,9 +4,12 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { AggregationsAutoDateHistogramAggregation } from '@elastic/elasticsearch/lib/api/types'; +import type { + AggregationsAggregationContainer, + AggregationsAutoDateHistogramAggregation, +} from '@elastic/elasticsearch/lib/api/types'; import type { QueryDslQueryContainer } from '@kbn/data-views-plugin/common/types'; -import type { AggregateOfMap, ChangePointType } from '@kbn/es-types/src/search'; +import type { AggregateOf, AggregateOfMap, ChangePointType } from '@kbn/es-types/src/search'; import type { ObservabilityAIAssistantElasticsearchClient } from '../../clients/elasticsearch'; type MetricType = 'min' | 'max' | 'sum' | 'count' | 'avg' | 'p95' | 'p99'; @@ -119,7 +122,8 @@ export async function getMetricChanges({ change_point: { buckets_path: 'over_time>value', }, - }, + // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 + } as AggregationsAggregationContainer, }; const response = await client.search('get_metric_changes', { @@ -146,6 +150,11 @@ export async function getMetricChanges({ const series = groups.map((group) => { const key = group.key ?? 'all'; + const changes = group.changes as AggregateOf< + { change_point: { buckets_path: string } }, + unknown + >; + return { key, over_time: group.over_time.buckets.map((bucket) => { @@ -155,12 +164,12 @@ export async function getMetricChanges({ }; }), changes: - group.changes.type.indeterminable || !group.changes.bucket?.key + changes.type.indeterminable || !changes.bucket?.key ? { type: 'indeterminable' as ChangePointType } : { - time: new Date(group.changes.bucket.key).toISOString(), - type: Object.keys(group.changes.type)[0] as keyof typeof group.changes.type, - ...Object.values(group.changes.type)[0], + time: new Date(changes.bucket.key).toISOString(), + type: Object.keys(changes.type)[0] as keyof typeof changes.type, + ...Object.values(changes.type)[0], }, }; }); diff --git a/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/create_shipper_api_key.ts b/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/create_shipper_api_key.ts index 9279ae0e1dfd1..d8dfd062c5e7b 100644 --- a/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/create_shipper_api_key.ts +++ b/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/create_shipper_api_key.ts @@ -15,17 +15,15 @@ import { export function createShipperApiKey(esClient: ElasticsearchClient, name: string, withAPM = false) { // Based on https://www.elastic.co/guide/en/fleet/master/grant-access-to-elasticsearch.html#create-api-key-standalone-agent return esClient.security.createApiKey({ - body: { - name, - metadata: { - managed: true, - application: 'logs', - }, - role_descriptors: { - standalone_agent: { - cluster: [MONITOR_CLUSTER], - indices: [withAPM ? INDEX_LOGS_METRICS_AND_TRACES : INDEX_LOGS_AND_METRICS], - }, + name, + metadata: { + managed: true, + application: 'logs', + }, + role_descriptors: { + standalone_agent: { + cluster: [MONITOR_CLUSTER], + indices: [withAPM ? INDEX_LOGS_METRICS_AND_TRACES : INDEX_LOGS_AND_METRICS], }, }, }); diff --git a/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/has_log_monitoring_privileges.ts b/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/has_log_monitoring_privileges.ts index ce5897936b741..71a4b2cbd55be 100644 --- a/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/has_log_monitoring_privileges.ts +++ b/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/has_log_monitoring_privileges.ts @@ -14,10 +14,8 @@ import { export async function hasLogMonitoringPrivileges(esClient: ElasticsearchClient, withAPM = false) { const res = await esClient.security.hasPrivileges({ - body: { - cluster: [MONITOR_CLUSTER, 'manage_own_api_key'], - index: [withAPM ? INDEX_LOGS_METRICS_AND_TRACES : INDEX_LOGS_AND_METRICS], - }, + cluster: [MONITOR_CLUSTER, 'manage_own_api_key'], + index: [withAPM ? INDEX_LOGS_METRICS_AND_TRACES : INDEX_LOGS_AND_METRICS], }); return res.has_all_requested; diff --git a/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/privileges.ts b/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/privileges.ts index 8a28849ef1003..0bee635aea2e2 100644 --- a/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/privileges.ts +++ b/x-pack/solutions/observability/plugins/observability_onboarding/server/lib/api_key/privileges.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; /** * Grants all cluster read-only operations, like cluster health and state, hot threads, node info, node and cluster stats, and pending cluster tasks. diff --git a/x-pack/solutions/observability/plugins/observability_shared/public/hooks/use_es_search.ts b/x-pack/solutions/observability/plugins/observability_shared/public/hooks/use_es_search.ts index 855d888c174df..20eec7aa6dbb0 100644 --- a/x-pack/solutions/observability/plugins/observability_shared/public/hooks/use_es_search.ts +++ b/x-pack/solutions/observability/plugins/observability_shared/public/hooks/use_es_search.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { ESSearchResponse } from '@kbn/es-types'; import { useKibana } from '@kbn/kibana-react-plugin/public'; diff --git a/x-pack/solutions/observability/plugins/profiling/common/topn.ts b/x-pack/solutions/observability/plugins/profiling/common/topn.ts index 79f8195fc4bd3..834deb1492459 100644 --- a/x-pack/solutions/observability/plugins/profiling/common/topn.ts +++ b/x-pack/solutions/observability/plugins/profiling/common/topn.ts @@ -126,7 +126,7 @@ export function getTopNAggregationRequest({ export function createTopNSamples( response: Required< - InferSearchResponseOf } }> + InferSearchResponseOf }> >['aggregations'], startMilliseconds: number, endMilliseconds: number, diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/downsampling.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/downsampling.ts index 12399298fe8d2..be924b5c70996 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/downsampling.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/downsampling.ts @@ -79,11 +79,9 @@ export async function findDownsampledIndex({ try { const resp = await client.search('find_downsampled_index', { index: getFullDownsampledIndex(index, initialExp, 5), - body: { - query: filter, - size: 0, - track_total_hits: true, - }, + query: filter, + size: 0, + track_total_hits: true, }); sampleCountFromInitialExp = resp.hits.total.value; } catch (e) { diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/query.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/query.ts index a160a7be82387..63c38843ec61c 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/query.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslBoolQuery } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslBoolQuery } from '@elastic/elasticsearch/lib/api/types'; import { kqlQuery } from '@kbn/observability-plugin/server'; import { ProfilingESField } from '@kbn/profiling-utils'; diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_daily_data_generation.size.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_daily_data_generation.size.ts index 19ce433b7aed6..eac368016c876 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_daily_data_generation.size.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_daily_data_generation.size.ts @@ -48,31 +48,29 @@ export async function getDailyDataGenerationSize({ 'profiling-hosts', 'profiling-metrics', ].join(), - body: { - query: { - bool: { - filter: { - ...kqlQuery(kuery), - range: { - '@timestamp': { - gte: String(timeFrom), - lt: String(timeTo), - format: 'epoch_second', - }, + query: { + bool: { + filter: { + ...kqlQuery(kuery), + range: { + '@timestamp': { + gte: String(timeFrom), + lt: String(timeTo), + format: 'epoch_second', }, }, }, }, - aggs: { - indices: { - terms: { - field: '_index', - }, - aggs: { - number_of_documents: { - value_count: { - field: '_index', - }, + }, + aggs: { + indices: { + terms: { + field: '_index', + }, + aggs: { + number_of_documents: { + value_count: { + field: '_index', }, }, }, diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_breakdown_size_timeseries.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_breakdown_size_timeseries.ts index 724654ff92a09..d72845f7a8771 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_breakdown_size_timeseries.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_breakdown_size_timeseries.ts @@ -37,43 +37,41 @@ export async function getHostBreakdownSizeTimeseries({ getIndicesStats({ client: client.getEsClient(), indices: allIndices }), client.search('profiling_events_metrics_size', { index: ['profiling-events-*', 'profiling-metrics'], - body: { - query: { - bool: { - filter: [ - ...kqlQuery(kuery), - { - range: { - [ProfilingESField.Timestamp]: { - gte: String(timeFrom), - lt: String(timeTo), - format: 'epoch_second', - }, + query: { + bool: { + filter: [ + ...kqlQuery(kuery), + { + range: { + [ProfilingESField.Timestamp]: { + gte: String(timeFrom), + lt: String(timeTo), + format: 'epoch_second', }, }, - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery('_tier', indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, - }, - aggs: { - hosts: { - terms: { - field: ProfilingESField.HostID, }, - aggs: { - storageTimeseries: { - date_histogram: { - field: ProfilingESField.Timestamp, - fixed_interval: `${bucketWidth}s`, - }, - aggs: { - indices: { - terms: { - field: '_index', - size: 500, - }, + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery('_tier', indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], + }, + }, + aggs: { + hosts: { + terms: { + field: ProfilingESField.HostID, + }, + aggs: { + storageTimeseries: { + date_histogram: { + field: ProfilingESField.Timestamp, + fixed_interval: `${bucketWidth}s`, + }, + aggs: { + indices: { + terms: { + field: '_index', + size: 500, }, }, }, diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_details.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_details.ts index 46df7974c2161..c2c8590f8abb6 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_details.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_details.ts @@ -36,42 +36,40 @@ export async function getHostDetails({ getIndicesStats({ client: client.getEsClient(), indices: allIndices }), client.search('profiling_events_metrics_details', { index: ['profiling-events-*', 'profiling-metrics'], - body: { - query: { - bool: { - filter: [ - ...kqlQuery(kuery), - { - range: { - [ProfilingESField.Timestamp]: { - gte: String(timeFrom), - lt: String(timeTo), - format: 'epoch_second', - }, + query: { + bool: { + filter: [ + ...kqlQuery(kuery), + { + range: { + [ProfilingESField.Timestamp]: { + gte: String(timeFrom), + lt: String(timeTo), + format: 'epoch_second', }, }, - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery('_tier', indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, - }, - aggs: { - hosts: { - terms: { - field: ProfilingESField.HostID, }, - aggs: { - projectIds: { - terms: { - field: 'profiling.project.id', - }, - aggs: { - indices: { - terms: { - field: '_index', - size: 500, - }, + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery('_tier', indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], + }, + }, + aggs: { + hosts: { + terms: { + field: ProfilingESField.HostID, + }, + aggs: { + projectIds: { + terms: { + field: 'profiling.project.id', + }, + aggs: { + indices: { + terms: { + field: '_index', + size: 500, }, }, }, diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_distinct_probabilistic_count.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_distinct_probabilistic_count.ts index b52107c976120..c5f31e6e8fd87 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_distinct_probabilistic_count.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_host_distinct_probabilistic_count.ts @@ -27,48 +27,46 @@ export async function getHostAndDistinctProbabilisticCount({ }) { const response = await client.search('profiling_probabilistic_cardinality', { index: 'profiling-hosts', - body: { - query: { - bool: { - filter: [ - ...kqlQuery(kuery), - { - range: { - '@timestamp': { - gte: String(timeFrom), - lt: String(timeTo), - format: 'epoch_second', - }, + query: { + bool: { + filter: [ + ...kqlQuery(kuery), + { + range: { + '@timestamp': { + gte: String(timeFrom), + lt: String(timeTo), + format: 'epoch_second', }, }, - ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All - ? termQuery('_tier', indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) - : []), - ], - }, - }, - aggs: { - hostsAndProjectIds: { - multi_terms: { - terms: [{ field: 'host.id' }, { field: 'profiling.project.id' }], }, - aggs: { - activeProbabilisticValue: { - top_metrics: { - metrics: { - field: 'profiling.agent.config.probabilistic_threshold', - }, - sort: { - '@timestamp': 'desc', - }, + ...(indexLifecyclePhase !== IndexLifecyclePhaseSelectOption.All + ? termQuery('_tier', indexLifeCyclePhaseToDataTier[indexLifecyclePhase]) + : []), + ], + }, + }, + aggs: { + hostsAndProjectIds: { + multi_terms: { + terms: [{ field: 'host.id' }, { field: 'profiling.project.id' }], + }, + aggs: { + activeProbabilisticValue: { + top_metrics: { + metrics: { + field: 'profiling.agent.config.probabilistic_threshold', + }, + sort: { + '@timestamp': 'desc', }, }, }, }, - hostCount: { - cardinality: { - field: 'host.id', - }, + }, + hostCount: { + cardinality: { + field: 'host.id', }, }, }, diff --git a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_profiling_hosts_details_by_id.ts b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_profiling_hosts_details_by_id.ts index 335ad08f4149d..26041badf4be1 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_profiling_hosts_details_by_id.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/routes/storage_explorer/get_profiling_hosts_details_by_id.ts @@ -33,53 +33,51 @@ export async function getProfilingHostsDetailsById({ }): Promise> { const resp = await client.search('get_host_ids_names', { index: 'profiling-hosts', - body: { - size: 0, - query: { - bool: { - filter: [ - { terms: { [ProfilingESField.HostID]: hostIds } }, - { - range: { - [ProfilingESField.Timestamp]: { - gte: String(timeFrom), - lt: String(timeTo), - format: 'epoch_second', - }, + size: 0, + query: { + bool: { + filter: [ + { terms: { [ProfilingESField.HostID]: hostIds } }, + { + range: { + [ProfilingESField.Timestamp]: { + gte: String(timeFrom), + lt: String(timeTo), + format: 'epoch_second', }, }, - ...kqlQuery(kuery), - ], - }, + }, + ...kqlQuery(kuery), + ], }, - aggs: { - hostIds: { - terms: { - field: ProfilingESField.HostID, + }, + aggs: { + hostIds: { + terms: { + field: ProfilingESField.HostID, + }, + aggs: { + hostNames: { + top_metrics: { + metrics: { field: 'profiling.host.name' }, + sort: '_score', + }, }, - aggs: { - hostNames: { - top_metrics: { - metrics: { field: 'profiling.host.name' }, - sort: '_score', - }, + projectIds: { + terms: { + field: 'profiling.project.id', }, - projectIds: { - terms: { - field: 'profiling.project.id', - }, - aggs: { - probabilisticValues: { - terms: { - field: 'profiling.agent.config.probabilistic_threshold', - size: 5, - order: { agentFirstStartDate: 'desc' }, - }, - aggs: { - agentFirstStartDate: { - min: { - field: 'profiling.agent.start_time', - }, + aggs: { + probabilisticValues: { + terms: { + field: 'profiling.agent.config.probabilistic_threshold', + size: 5, + order: { agentFirstStartDate: 'desc' }, + }, + aggs: { + agentFirstStartDate: { + min: { + field: 'profiling.agent.start_time', }, }, }, diff --git a/x-pack/solutions/observability/plugins/profiling/server/utils/create_profiling_es_client.ts b/x-pack/solutions/observability/plugins/profiling/server/utils/create_profiling_es_client.ts index aca25abfd56f2..c4105052725b5 100644 --- a/x-pack/solutions/observability/plugins/profiling/server/utils/create_profiling_es_client.ts +++ b/x-pack/solutions/observability/plugins/profiling/server/utils/create_profiling_es_client.ts @@ -9,7 +9,7 @@ import type { ElasticsearchClient } from '@kbn/core/server'; import type { ESSearchRequest, InferSearchResponseOf } from '@kbn/es-types'; import type { KibanaRequest } from '@kbn/core/server'; import { unwrapEsResponse } from '@kbn/observability-plugin/server'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { AggregationField, BaseFlameGraph, diff --git a/x-pack/solutions/observability/plugins/profiling_data_access/common/profiling_es_client.ts b/x-pack/solutions/observability/plugins/profiling_data_access/common/profiling_es_client.ts index c5cf84389f951..87167c5f4de34 100644 --- a/x-pack/solutions/observability/plugins/profiling_data_access/common/profiling_es_client.ts +++ b/x-pack/solutions/observability/plugins/profiling_data_access/common/profiling_es_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { ESSearchRequest, InferSearchResponseOf } from '@kbn/es-types'; import type { diff --git a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/fetch_flamechart/index.ts b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/fetch_flamechart/index.ts index 9280cba74579f..34893ef10828a 100644 --- a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/fetch_flamechart/index.ts +++ b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/fetch_flamechart/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { CoreRequestHandlerContext, ElasticsearchClient } from '@kbn/core/server'; import { profilingAWSCostDiscountRate, diff --git a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/es_functions.ts b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/es_functions.ts index 9c712b4283052..6fdd536c7b07d 100644 --- a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/es_functions.ts +++ b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/es_functions.ts @@ -14,7 +14,7 @@ import { profilingAzureCostDiscountRate, profilingShowErrorFrames, } from '@kbn/observability-plugin/common'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { CoreRequestHandlerContext, ElasticsearchClient } from '@kbn/core/server'; import type { AggregationField, ESTopNFunctions, TopNFunctions } from '@kbn/profiling-utils'; import { convertTonsToKgs } from '@kbn/profiling-utils'; diff --git a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/index.ts b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/index.ts index fe1d8340931d7..c0557cf26b1d1 100644 --- a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/index.ts +++ b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/functions/index.ts @@ -16,7 +16,7 @@ import { } from '@kbn/observability-plugin/common'; import type { CoreRequestHandlerContext, ElasticsearchClient } from '@kbn/core/server'; import { createTopNFunctions } from '@kbn/profiling-utils'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { percentToFactor } from '../../utils/percent_to_factor'; import { withProfilingSpan } from '../../utils/with_profiling_span'; import type { RegisterServicesParams } from '../register_services'; diff --git a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/search_stack_traces/index.ts b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/search_stack_traces/index.ts index d246ceaf96104..6ff93dbec2668 100644 --- a/x-pack/solutions/observability/plugins/profiling_data_access/server/services/search_stack_traces/index.ts +++ b/x-pack/solutions/observability/plugins/profiling_data_access/server/services/search_stack_traces/index.ts @@ -6,7 +6,7 @@ */ import { decodeStackTraceResponse } from '@kbn/profiling-utils'; -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ProfilingESClient } from '../../../common/profiling_es_client'; interface Params { diff --git a/x-pack/solutions/observability/plugins/profiling_data_access/server/utils/query.ts b/x-pack/solutions/observability/plugins/profiling_data_access/server/utils/query.ts index 106e95c40a7f7..2f560157cc8c6 100644 --- a/x-pack/solutions/observability/plugins/profiling_data_access/server/utils/query.ts +++ b/x-pack/solutions/observability/plugins/profiling_data_access/server/utils/query.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; export function kqlQuery(kql?: string): estypes.QueryDslQueryContainer[] { diff --git a/x-pack/solutions/observability/plugins/slo/common/parse_kuery.ts b/x-pack/solutions/observability/plugins/slo/common/parse_kuery.ts index de4dd3c238bad..c5c5f436819af 100644 --- a/x-pack/solutions/observability/plugins/slo/common/parse_kuery.ts +++ b/x-pack/solutions/observability/plugins/slo/common/parse_kuery.ts @@ -24,6 +24,7 @@ export function getElasticsearchQueryOrThrow(kuery: QuerySchema = ''): QueryDslQ ); } } catch (err) { - return [] as QueryDslQueryContainer; + // @ts-expect-error `getElasticsearchQueryOrThrow` but it doesn't throw :shrug: + return []; } } diff --git a/x-pack/solutions/observability/plugins/slo/public/hooks/use_fetch_global_diagnosis.ts b/x-pack/solutions/observability/plugins/slo/public/hooks/use_fetch_global_diagnosis.ts index d943322cf1322..8cbb595d37e71 100644 --- a/x-pack/solutions/observability/plugins/slo/public/hooks/use_fetch_global_diagnosis.ts +++ b/x-pack/solutions/observability/plugins/slo/public/hooks/use_fetch_global_diagnosis.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SecurityHasPrivilegesResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SecurityHasPrivilegesResponse } from '@elastic/elasticsearch/lib/api/types'; import { i18n } from '@kbn/i18n'; import type { PublicLicenseJSON } from '@kbn/licensing-plugin/public'; import { useQuery } from '@tanstack/react-query'; diff --git a/x-pack/solutions/observability/plugins/slo/server/lib/rules/slo_burn_rate/lib/summary_repository.ts b/x-pack/solutions/observability/plugins/slo/server/lib/rules/slo_burn_rate/lib/summary_repository.ts index 67c4deedbe332..e77f26b95ccee 100644 --- a/x-pack/solutions/observability/plugins/slo/server/lib/rules/slo_burn_rate/lib/summary_repository.ts +++ b/x-pack/solutions/observability/plugins/slo/server/lib/rules/slo_burn_rate/lib/summary_repository.ts @@ -18,18 +18,16 @@ export async function getSloSummary( try { const res = await esClient.search({ index: SUMMARY_DESTINATION_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - { term: { 'slo.id': slo.id } }, - { term: { 'slo.revision': slo.revision } }, - { term: { 'slo.instanceId': instanceId } }, - ], - }, + query: { + bool: { + filter: [ + { term: { 'slo.id': slo.id } }, + { term: { 'slo.revision': slo.revision } }, + { term: { 'slo.instanceId': instanceId } }, + ], }, - size: 1, }, + size: 1, }); if (res.hits.hits.length === 0) { diff --git a/x-pack/solutions/observability/plugins/slo/server/services/aggregations/get_histogram_indicator_aggregation.ts b/x-pack/solutions/observability/plugins/slo/server/services/aggregations/get_histogram_indicator_aggregation.ts index 3415e797d21b6..6ed3643af0e6a 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/aggregations/get_histogram_indicator_aggregation.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/aggregations/get_histogram_indicator_aggregation.ts @@ -6,7 +6,7 @@ */ import { HistogramIndicator } from '@kbn/slo-schema'; -import { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import { getElasticsearchQueryOrThrow } from '../transform_generators/common'; type HistogramIndicatorDef = diff --git a/x-pack/solutions/observability/plugins/slo/server/services/burn_rates_client.ts b/x-pack/solutions/observability/plugins/slo/server/services/burn_rates_client.ts index 0897afbe9bcc1..68e173486b85d 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/burn_rates_client.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/burn_rates_client.ts @@ -12,7 +12,7 @@ import { AggregationsValueCountAggregate, MsearchMultisearchBody, QueryDslQueryContainer, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient } from '@kbn/core/server'; import { ALL_VALUE, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/create_slo.ts b/x-pack/solutions/observability/plugins/slo/server/services/create_slo.ts index 0bc5500b2782c..e135e35119a2f 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/create_slo.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/create_slo.ts @@ -5,7 +5,7 @@ * 2.0. */ import { IngestPutPipelineRequest } from '@elastic/elasticsearch/lib/api/types'; -import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, IBasePath, IScopedClusterClient, Logger } from '@kbn/core/server'; import { ALL_VALUE, CreateSLOParams, CreateSLOResponse } from '@kbn/slo-schema'; import { asyncForEach } from '@kbn/std'; @@ -193,9 +193,7 @@ export class CreateSLO { temporaryDoc, summaryTransform, rollUpTransform, - // @ts-expect-error there is some issue with deprecated types being used in es types rollUpTransformCompositeQuery: getTransformQueryComposite(rollUpTransform), - // @ts-expect-error there is some issue with deprecated types being used in es types summaryTransformCompositeQuery: getTransformQueryComposite(summaryTransform), }; } diff --git a/x-pack/solutions/observability/plugins/slo/server/services/find_slo_groups.ts b/x-pack/solutions/observability/plugins/slo/server/services/find_slo_groups.ts index d33bd0badfc9c..e9f6b8533650e 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/find_slo_groups.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/find_slo_groups.ts @@ -70,82 +70,80 @@ export class FindSLOGroups { must_not: [...(parsedFilters.must_not ?? [])], }, }, - body: { - aggs: { - groupBy: { - terms: { - field: groupBy, - size: 10000, - ...(hasSelectedTags && { include: groupsFilter }), - }, - aggs: { - worst: { - top_hits: { - sort: { - errorBudgetRemaining: { - order: 'asc', - }, - }, - _source: { - includes: [ - 'sliValue', - 'status', - 'slo.id', - 'slo.instanceId', - 'slo.name', - 'slo.groupings', - ], + aggs: { + groupBy: { + terms: { + field: groupBy, + size: 10000, + ...(hasSelectedTags && { include: groupsFilter }), + }, + aggs: { + worst: { + top_hits: { + sort: { + errorBudgetRemaining: { + order: 'asc', }, - size: 1, }, + _source: { + includes: [ + 'sliValue', + 'status', + 'slo.id', + 'slo.instanceId', + 'slo.name', + 'slo.groupings', + ], + }, + size: 1, }, - violated: { - filter: { - term: { - status: 'VIOLATED', - }, + }, + violated: { + filter: { + term: { + status: 'VIOLATED', }, }, - healthy: { - filter: { - term: { - status: 'HEALTHY', - }, + }, + healthy: { + filter: { + term: { + status: 'HEALTHY', }, }, - degrading: { - filter: { - term: { - status: 'DEGRADING', - }, + }, + degrading: { + filter: { + term: { + status: 'DEGRADING', }, }, - noData: { - filter: { - term: { - status: 'NO_DATA', - }, + }, + noData: { + filter: { + term: { + status: 'NO_DATA', }, }, + }, + bucket_sort: { bucket_sort: { - bucket_sort: { - sort: [ - { - _key: { - order: 'asc', - }, + sort: [ + { + _key: { + order: 'asc', }, - ], - from: (pagination.page - 1) * pagination.perPage, - size: pagination.perPage, - }, + }, + ], + from: (pagination.page - 1) * pagination.perPage, + size: pagination.perPage, }, }, }, - distinct_items: { - cardinality: { - field: groupBy, - }, + }, + distinct_items: { + cardinality: { + field: groupBy, }, }, }, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/get_preview_data.ts b/x-pack/solutions/observability/plugins/slo/server/services/get_preview_data.ts index db95680ecd655..4289cef618819 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/get_preview_data.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/get_preview_data.ts @@ -20,7 +20,7 @@ import { import { assertNever } from '@kbn/std'; import moment from 'moment'; import { ElasticsearchClient } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DataView, DataViewsService } from '@kbn/data-views-plugin/common'; import { getElasticsearchQueryOrThrow } from './transform_generators'; diff --git a/x-pack/solutions/observability/plugins/slo/server/services/get_slo_health.test.ts b/x-pack/solutions/observability/plugins/slo/server/services/get_slo_health.test.ts index a6553e6f069aa..245dffa398651 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/get_slo_health.test.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/get_slo_health.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { TransformGetTransformStatsTransformStats } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { TransformGetTransformStatsTransformStats } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient } from '@kbn/core/server'; import { ScopedClusterClientMock, elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { ALL_VALUE } from '@kbn/slo-schema'; diff --git a/x-pack/solutions/observability/plugins/slo/server/services/get_slo_stats_overview.ts b/x-pack/solutions/observability/plugins/slo/server/services/get_slo_stats_overview.ts index 34fc421ad4b39..9df83dbdef239 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/get_slo_stats_overview.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/get_slo_stats_overview.ts @@ -48,52 +48,50 @@ export class GetSLOStatsOverview { must_not: [...(parsedFilters.must_not ?? [])], }, }, - body: { - aggs: { - stale: { - filter: { - range: { - summaryUpdatedAt: { - lt: `now-${settings.staleThresholdInHours}h`, - }, + aggs: { + stale: { + filter: { + range: { + summaryUpdatedAt: { + lt: `now-${settings.staleThresholdInHours}h`, }, }, }, - not_stale: { - filter: { - range: { - summaryUpdatedAt: { - gte: `now-${settings.staleThresholdInHours}h`, - }, + }, + not_stale: { + filter: { + range: { + summaryUpdatedAt: { + gte: `now-${settings.staleThresholdInHours}h`, }, }, - aggs: { - violated: { - filter: { - term: { - status: 'VIOLATED', - }, + }, + aggs: { + violated: { + filter: { + term: { + status: 'VIOLATED', }, }, - healthy: { - filter: { - term: { - status: 'HEALTHY', - }, + }, + healthy: { + filter: { + term: { + status: 'HEALTHY', }, }, - degrading: { - filter: { - term: { - status: 'DEGRADING', - }, + }, + degrading: { + filter: { + term: { + status: 'DEGRADING', }, }, - noData: { - filter: { - term: { - status: 'NO_DATA', - }, + }, + noData: { + filter: { + term: { + status: 'NO_DATA', }, }, }, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/historical_summary_client.ts b/x-pack/solutions/observability/plugins/slo/server/services/historical_summary_client.ts index cdabfb76dc379..eb19146a5630a 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/historical_summary_client.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/historical_summary_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { MsearchMultisearchBody } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { MsearchMultisearchBody } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient } from '@kbn/core/server'; import { ALL_VALUE, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/management/__snapshots__/clean_up_temp_summary.test.ts.snap b/x-pack/solutions/observability/plugins/slo/server/services/management/__snapshots__/clean_up_temp_summary.test.ts.snap index ff135676c7e29..dfb343c41bf8d 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/management/__snapshots__/clean_up_temp_summary.test.ts.snap +++ b/x-pack/solutions/observability/plugins/slo/server/services/management/__snapshots__/clean_up_temp_summary.test.ts.snap @@ -5,38 +5,36 @@ exports[`CleanUpTempSummary deletes the duplicated temp documents 1`] = ` "calls": Array [ Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "must": Array [ - Object { - "term": Object { - "isTempDoc": true, - }, + "conflicts": "proceed", + "index": ".slo-observability.summary-v3.4.temp", + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "must": Array [ + Object { + "term": Object { + "isTempDoc": true, }, - Object { - "term": Object { - "slo.id": "slo-id-one", - }, + }, + Object { + "term": Object { + "slo.id": "slo-id-one", }, - Object { - "term": Object { - "spaceId": "space-one", - }, + }, + Object { + "term": Object { + "spaceId": "space-one", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, }, - "conflicts": "proceed", - "index": ".slo-observability.summary-v3.4.temp", "slices": "auto", "wait_for_completion": false, }, @@ -46,38 +44,36 @@ exports[`CleanUpTempSummary deletes the duplicated temp documents 1`] = ` ], Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "must": Array [ - Object { - "term": Object { - "isTempDoc": true, - }, + "conflicts": "proceed", + "index": ".slo-observability.summary-v3.4.temp", + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "must": Array [ + Object { + "term": Object { + "isTempDoc": true, }, - Object { - "term": Object { - "slo.id": "another-temp-id", - }, + }, + Object { + "term": Object { + "slo.id": "another-temp-id", }, - Object { - "term": Object { - "spaceId": "space-two", - }, + }, + Object { + "term": Object { + "spaceId": "space-two", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, }, - "conflicts": "proceed", - "index": ".slo-observability.summary-v3.4.temp", "slices": "auto", "wait_for_completion": false, }, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/management/clean_up_temp_summary.ts b/x-pack/solutions/observability/plugins/slo/server/services/management/clean_up_temp_summary.ts index fbe675d825aaf..83d34da0ad0f4 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/management/clean_up_temp_summary.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/management/clean_up_temp_summary.ts @@ -128,34 +128,32 @@ export class CleanUpTempSummary { wait_for_completion: false, slices: 'auto', conflicts: 'proceed', - body: { - query: { - bool: { - should: buckets.map((bucket) => { - return { - bool: { - must: [ - { - term: { - isTempDoc: true, - }, + query: { + bool: { + should: buckets.map((bucket) => { + return { + bool: { + must: [ + { + term: { + isTempDoc: true, }, - { - term: { - 'slo.id': bucket.id, - }, + }, + { + term: { + 'slo.id': bucket.id, }, - { - term: { - spaceId: bucket.spaceId, - }, + }, + { + term: { + spaceId: bucket.spaceId, }, - ], - }, - }; - }), - minimum_should_match: 1, - }, + }, + ], + }, + }; + }), + minimum_should_match: 1, }, }, }, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/summary_client.ts b/x-pack/solutions/observability/plugins/slo/server/services/summary_client.ts index bb98c4443f0f2..eedc1ff60cbc8 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/summary_client.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/summary_client.ts @@ -9,7 +9,7 @@ import { AggregationsValueCountAggregate } from '@elastic/elasticsearch/lib/api/ import { AggregationsSumAggregate, AggregationsTopHitsAggregate, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient } from '@kbn/core/server'; import { ALL_VALUE, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/summary_search_client/summary_search_client.ts b/x-pack/solutions/observability/plugins/slo/server/services/summary_search_client/summary_search_client.ts index 3dd91cbbf41b4..3cdae8788d06c 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/summary_search_client/summary_search_client.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/summary_search_client/summary_search_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient, Logger, SavedObjectsClientContract } from '@kbn/core/server'; import { isCCSRemoteIndexName } from '@kbn/es-query'; import { ALL_VALUE } from '@kbn/slo-schema'; diff --git a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_duration.ts b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_duration.ts index fe0d610bee888..a140fcae0ada1 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_duration.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_duration.ts @@ -5,9 +5,11 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; -import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/types'; -import { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; +import type { + TransformPutTransformRequest, + AggregationsAggregationContainer, +} from '@elastic/elasticsearch/lib/api/types'; import { DataViewsService } from '@kbn/data-views-plugin/common'; import { ALL_VALUE, diff --git a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_error_rate.ts b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_error_rate.ts index 88955828dd955..3f6fc7ae60ccb 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_error_rate.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/apm_transaction_error_rate.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/types'; import { DataViewsService } from '@kbn/data-views-plugin/common'; import { diff --git a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/synthetics_availability.ts b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/synthetics_availability.ts index e05fe886421b0..d0c464956814f 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/synthetics_availability.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/synthetics_availability.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/types'; import { DataViewsService } from '@kbn/data-views-plugin/common'; import { diff --git a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/transform_generator.ts b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/transform_generator.ts index ea27ebbc7aa38..e48e9e4477fe9 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/transform_generator.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/transform_generators/transform_generator.ts @@ -8,7 +8,7 @@ import { MappingRuntimeFields, TransformPutTransformRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { DataView, DataViewsService } from '@kbn/data-views-plugin/common'; import { ALL_VALUE, timeslicesBudgetingMethodSchema } from '@kbn/slo-schema'; import { TransformSettings } from '../../assets/transform_templates/slo_transform_template'; diff --git a/x-pack/solutions/observability/plugins/slo/server/services/transform_manager.ts b/x-pack/solutions/observability/plugins/slo/server/services/transform_manager.ts index e95b04ca6b7da..0c0666246b66e 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/transform_manager.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/transform_manager.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/types'; import { IScopedClusterClient, Logger } from '@kbn/core/server'; import { IndicatorTypes, SLODefinition } from '../domain/models'; import { SecurityException } from '../errors'; diff --git a/x-pack/solutions/observability/plugins/slo/server/services/utils/get_transform_compite_query.ts b/x-pack/solutions/observability/plugins/slo/server/services/utils/get_transform_compite_query.ts index 6ed34a9cd0aa4..8fa80db233b6e 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/utils/get_transform_compite_query.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/utils/get_transform_compite_query.ts @@ -8,33 +8,31 @@ import { AggregationsCompositeAggregationSource, TransformPutTransformRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { createEsParams } from '../../utils/queries'; -export function getTransformQueryComposite(transform: TransformPutTransformRequest['body']) { +export function getTransformQueryComposite(transform: TransformPutTransformRequest) { let transformQueryString: string = ''; if (transform) { const pivotGroupBy = transform.pivot?.group_by ?? {}; const transformQuery = createEsParams({ - body: { - size: 0, - query: transform.source.query, - runtime_mappings: transform.source.runtime_mappings, - aggs: { - groupBy: { - composite: { - sources: Object.keys(pivotGroupBy).map((key) => ({ - [key]: pivotGroupBy[key] as AggregationsCompositeAggregationSource, - })), - }, - aggs: transform?.pivot?.aggregations, + size: 0, + query: transform.source.query, + runtime_mappings: transform.source.runtime_mappings, + aggs: { + groupBy: { + composite: { + sources: Object.keys(pivotGroupBy).map((key) => ({ + [key]: pivotGroupBy[key] as AggregationsCompositeAggregationSource, + })), }, + aggs: transform?.pivot?.aggregations, }, }, }); transformQueryString = `POST ${transform.source.index}/_search\n${JSON.stringify( - transformQuery.body, + transformQuery, null, 2 )}`; diff --git a/x-pack/solutions/observability/plugins/slo/server/utils/queries.ts b/x-pack/solutions/observability/plugins/slo/server/utils/queries.ts index fa581df62e745..f7cfcf3707465 100644 --- a/x-pack/solutions/observability/plugins/slo/server/utils/queries.ts +++ b/x-pack/solutions/observability/plugins/slo/server/utils/queries.ts @@ -6,7 +6,7 @@ */ import { reject } from 'lodash'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { ESSearchResponse } from '@kbn/es-types'; import { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; diff --git a/x-pack/solutions/observability/plugins/synthetics/common/requests/get_certs_request_body.ts b/x-pack/solutions/observability/plugins/synthetics/common/requests/get_certs_request_body.ts index 31f389a909004..93859d66ec685 100644 --- a/x-pack/solutions/observability/plugins/synthetics/common/requests/get_certs_request_body.ts +++ b/x-pack/solutions/observability/plugins/synthetics/common/requests/get_certs_request_body.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import DateMath from '@kbn/datemath'; import { EXCLUDE_RUN_ONCE_FILTER, FINAL_SUMMARY_FILTER } from '../constants/client_defaults'; import type { CertificatesResults } from '../../server/queries/get_certs'; @@ -47,136 +47,132 @@ export const getCertsRequestBody = ({ const sort = SortFields[sortBy as keyof typeof SortFields]; const searchRequest = createEsQuery({ - body: { - from: (pageIndex ?? 0) * size, - size, - sort: asMutableArray([ - { - [sort]: { - order: direction, - }, + from: (pageIndex ?? 0) * size, + size, + sort: asMutableArray([ + { + [sort]: { + order: direction, }, - ]) as estypes.SortCombinations[], - query: { - bool: { - ...(search - ? { - minimum_should_match: 1, - should: [ - { - multi_match: { - query: escape(search), - type: 'phrase_prefix' as const, - fields: [ - 'monitor.id.text', - 'monitor.name.text', - 'url.full.text', - 'tls.server.x509.subject.common_name.text', - 'tls.server.x509.issuer.common_name.text', - ], - }, + }, + ]) as estypes.SortCombinations[], + query: { + bool: { + ...(search + ? { + minimum_should_match: 1, + should: [ + { + multi_match: { + query: escape(search), + type: 'phrase_prefix' as const, + fields: [ + 'monitor.id.text', + 'monitor.name.text', + 'url.full.text', + 'tls.server.x509.subject.common_name.text', + 'tls.server.x509.issuer.common_name.text', + ], }, - ], - } - : {}), - filter: [ - FINAL_SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - ...(filters ? [filters] : []), - ...(monitorIds && monitorIds.length > 0 - ? [{ terms: { 'monitor.id': monitorIds } }] - : []), - { - exists: { - field: 'tls.server.hash.sha256', - }, - }, - { - range: { - 'monitor.timespan': { - gte: absoluteDate(from), - lte: absoluteDate(to), }, + ], + } + : {}), + filter: [ + FINAL_SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + ...(filters ? [filters] : []), + ...(monitorIds && monitorIds.length > 0 ? [{ terms: { 'monitor.id': monitorIds } }] : []), + { + exists: { + field: 'tls.server.hash.sha256', + }, + }, + { + range: { + 'monitor.timespan': { + gte: absoluteDate(from), + lte: absoluteDate(to), }, }, - { - bool: { - // these notValidBefore and notValidAfter should be inside should block, since - // we want to match either of the condition, making ir an OR operation - minimum_should_match: 1, - should: [ - ...(notValidBefore - ? [ - { - range: { - 'tls.certificate_not_valid_before': { - lte: absoluteDate(notValidBefore), - }, + }, + { + bool: { + // these notValidBefore and notValidAfter should be inside should block, since + // we want to match either of the condition, making ir an OR operation + minimum_should_match: 1, + should: [ + ...(notValidBefore + ? [ + { + range: { + 'tls.certificate_not_valid_before': { + lte: absoluteDate(notValidBefore), }, }, - ] - : []), - ...(notValidAfter - ? [ - { - range: { - 'tls.certificate_not_valid_after': { - lte: absoluteDate(notValidAfter), - }, + }, + ] + : []), + ...(notValidAfter + ? [ + { + range: { + 'tls.certificate_not_valid_after': { + lte: absoluteDate(notValidAfter), }, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, - ] as estypes.QueryDslQueryContainer, - }, - }, - _source: [ - '@timestamp', - 'config_id', - 'monitor.id', - 'monitor.name', - 'monitor.type', - 'url.full', - 'observer.geo.name', - 'tls.server.x509.issuer.common_name', - 'tls.server.x509.subject.common_name', - 'tls.server.hash.sha1', - 'tls.server.hash.sha256', - 'tls.server.x509.not_after', - 'tls.server.x509.not_before', - 'service', - 'labels', - 'tags', - 'error', - ], - collapse: { - field: 'tls.server.hash.sha256', - inner_hits: { - size: 100, - _source: { - includes: ['monitor.id', 'monitor.name', 'url.full', 'config_id'], }, - collapse: { - field: 'monitor.id', - }, - name: 'monitors', - sort: [{ 'monitor.id': 'asc' as const }], + ] as estypes.QueryDslQueryContainer, + }, + }, + _source: [ + '@timestamp', + 'config_id', + 'monitor.id', + 'monitor.name', + 'monitor.type', + 'url.full', + 'observer.geo.name', + 'tls.server.x509.issuer.common_name', + 'tls.server.x509.subject.common_name', + 'tls.server.hash.sha1', + 'tls.server.hash.sha256', + 'tls.server.x509.not_after', + 'tls.server.x509.not_before', + 'service', + 'labels', + 'tags', + 'error', + ], + collapse: { + field: 'tls.server.hash.sha256', + inner_hits: { + size: 100, + _source: { + includes: ['monitor.id', 'monitor.name', 'url.full', 'config_id'], + }, + collapse: { + field: 'monitor.id', }, + name: 'monitors', + sort: [{ 'monitor.id': 'asc' as const }], }, - aggs: { - total: { - cardinality: { - field: 'tls.server.hash.sha256', - }, + }, + aggs: { + total: { + cardinality: { + field: 'tls.server.hash.sha256', }, }, }, }); - return searchRequest.body; + return searchRequest; }; export const processCertsResult = (result: CertificatesResults): CertResult => { diff --git a/x-pack/solutions/observability/plugins/synthetics/common/utils/es_search.ts b/x-pack/solutions/observability/plugins/synthetics/common/utils/es_search.ts index 6a41b83d19ee0..6a136f3a5d0e7 100644 --- a/x-pack/solutions/observability/plugins/synthetics/common/utils/es_search.ts +++ b/x-pack/solutions/observability/plugins/synthetics/common/utils/es_search.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export function createEsQuery(params: T): T { return params; diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/common/components/use_std_error_logs.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/common/components/use_std_error_logs.ts index e2fcd33163fd1..3368e68eabb86 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/common/components/use_std_error_logs.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/common/components/use_std_error_logs.ts @@ -13,27 +13,25 @@ export const useStdErrorLogs = ({ checkGroup }: { checkGroup?: string }) => { const { data, loading } = useEsSearch( createEsParams({ index: !checkGroup ? '' : SYNTHETICS_INDEX_PATTERN, - body: { - size: 1000, - query: { - bool: { - filter: [ - { - terms: { - 'synthetics.type': ['stderr', 'stdout'], - }, + size: 1000, + query: { + bool: { + filter: [ + { + terms: { + 'synthetics.type': ['stderr', 'stdout'], }, - ...(checkGroup - ? [ - { - term: { - 'monitor.check_group': checkGroup, - }, + }, + ...(checkGroup + ? [ + { + term: { + 'monitor.check_group': checkGroup, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, }, }), diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_error_failed_tests.tsx b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_error_failed_tests.tsx index 18d4ae204dfbf..dc56f5ab038d4 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_error_failed_tests.tsx +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_error_failed_tests.tsx @@ -27,25 +27,23 @@ export function useErrorFailedTests() { const { data, loading } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 10000, - query: { - bool: { - filter: [ - SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - { - term: { - 'state.id': errorStateId, - }, + size: 10000, + query: { + bool: { + filter: [ + SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + { + term: { + 'state.id': errorStateId, }, - { - term: { - config_id: monitorId, - }, + }, + { + term: { + config_id: monitorId, }, - ], - }, + }, + ], }, sort: [{ '@timestamp': 'desc' }], }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_find_my_killer_state.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_find_my_killer_state.ts index 88e23cb6dcfae..b0f06028e7146 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_find_my_killer_state.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/error_details/hooks/use_find_my_killer_state.ts @@ -28,34 +28,32 @@ export function useFindMyKillerState() { { index: SYNTHETICS_INDEX_PATTERN, - body: { - // TODO: remove this once we have a better way to handle this mapping - runtime_mappings: { - 'state.ends.id': { - type: 'keyword', - }, + // TODO: remove this once we have a better way to handle this mapping + runtime_mappings: { + 'state.ends.id': { + type: 'keyword', }, - size: 1, - query: { - bool: { - filter: [ - FINAL_SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - { - term: { - 'state.ends.id': errorStateId, - }, + }, + size: 1, + query: { + bool: { + filter: [ + FINAL_SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + { + term: { + 'state.ends.id': errorStateId, }, - { - term: { - config_id: monitorId, - }, + }, + { + term: { + config_id: monitorId, }, - ], - }, + }, + ], }, - sort: [{ '@timestamp': 'desc' }], }, + sort: [{ '@timestamp': 'desc' }], }, [lastRefresh, monitorId, dateRangeStart, dateRangeEnd], { name: 'getStateWhichEndTheState' } diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_error_failed_step.tsx b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_error_failed_step.tsx index 75a8a5eeee96c..a31735b15d2fa 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_error_failed_step.tsx +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_error_failed_step.tsx @@ -8,7 +8,7 @@ import { useEsSearch } from '@kbn/observability-shared-plugin/public'; import { useParams } from 'react-router-dom'; import { useMemo } from 'react'; -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { STEP_END_FILTER } from '../../../../../../common/constants/data_filters'; import { asMutableArray } from '../../../../../../common/utils/as_mutable_array'; import { Ping } from '../../../../../../common/runtime_types'; @@ -23,31 +23,29 @@ export function useErrorFailedStep(checkGroups: string[]) { const { data, loading } = useEsSearch( { index: checkGroups?.length > 0 ? SYNTHETICS_INDEX_PATTERN : '', - body: { - size: checkGroups.length, - query: { - bool: { - filter: [ - STEP_END_FILTER, - { - exists: { - field: 'synthetics.error', - }, + size: checkGroups.length, + query: { + bool: { + filter: [ + STEP_END_FILTER, + { + exists: { + field: 'synthetics.error', }, - { - terms: { - 'monitor.check_group': checkGroups, - }, + }, + { + terms: { + 'monitor.check_group': checkGroups, }, - ] as QueryDslQueryContainer[], - }, + }, + ] as QueryDslQueryContainer[], }, - sort: asMutableArray([ - { 'synthetics.step.index': { order: 'asc' } }, - { '@timestamp': { order: 'asc' } }, - ] as const), - _source: ['synthetics.step', 'synthetics.error', 'monitor.check_group'], }, + sort: asMutableArray([ + { 'synthetics.step.index': { order: 'asc' } }, + { '@timestamp': { order: 'asc' } }, + ] as const), + _source: ['synthetics.step', 'synthetics.error', 'monitor.check_group'], }, [lastRefresh, monitorId, checkGroups], { name: 'getMonitorErrorFailedStep' } diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_failed_tests_by_step.tsx b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_failed_tests_by_step.tsx index f6688c0f8c1dc..d42e52d02e190 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_failed_tests_by_step.tsx +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_failed_tests_by_step.tsx @@ -24,50 +24,48 @@ export function useFailedTestByStep({ to, from }: { to: string; from: string }) const params = createEsQuery({ index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - track_total_hits: true, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - lte: to, - gte: from, - }, + size: 0, + track_total_hits: true, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + lte: to, + gte: from, }, }, - STEP_END_FILTER, - { - term: { - 'synthetics.step.status': 'failed', - }, + }, + STEP_END_FILTER, + { + term: { + 'synthetics.step.status': 'failed', }, - { - term: { - 'observer.geo.name': selectedLocation?.label, - }, + }, + { + term: { + 'observer.geo.name': selectedLocation?.label, }, - { - term: { - config_id: monitorId, - }, + }, + { + term: { + config_id: monitorId, }, - ], - }, - }, - aggs: { - steps: { - terms: { - field: 'synthetics.step.name.keyword', - size: 1000, }, - aggs: { - doc: { - top_hits: { - size: 1, - }, + ], + }, + }, + aggs: { + steps: { + terms: { + field: 'synthetics.step.name.keyword', + size: 1000, + }, + aggs: { + doc: { + top_hits: { + size: 1, }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_monitor_errors.tsx b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_monitor_errors.tsx index 5a7673f0513d5..72a8dc57ea54a 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_monitor_errors.tsx +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitor_details/hooks/use_monitor_errors.tsx @@ -32,60 +32,58 @@ export function useMonitorErrors(monitorIdArg?: string) { const { data, loading } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - query: { - bool: { - filter: [ - SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - { - range: { - '@timestamp': { - gte: dateRangeStart, - lte: dateRangeEnd, - time_zone: timeZone, - }, + size: 0, + query: { + bool: { + filter: [ + SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + { + range: { + '@timestamp': { + gte: dateRangeStart, + lte: dateRangeEnd, + time_zone: timeZone, }, }, - { - term: { - config_id: monitorIdArg ?? monitorId, - }, - }, - { - term: { - 'observer.geo.name': selectedLocation?.label, - }, + }, + { + term: { + config_id: monitorIdArg ?? monitorId, }, - ], - }, - }, - sort: [{ 'state.started_at': 'desc' }], - aggs: { - states: { - terms: { - field: 'state.id', - size: 10000, }, - aggs: { - summary: { - top_hits: { - size: 1, - _source: ['error', 'state', 'monitor', '@timestamp'], - sort: [{ '@timestamp': 'desc' }], - }, + { + term: { + 'observer.geo.name': selectedLocation?.label, }, }, + ], + }, + }, + sort: [{ 'state.started_at': 'desc' }], + aggs: { + states: { + terms: { + field: 'state.id', + size: 10000, }, - latest: { - top_hits: { - size: 1, - _source: ['monitor.status'], - sort: [{ '@timestamp': 'desc' }], + aggs: { + summary: { + top_hits: { + size: 1, + _source: ['error', 'state', 'monitor', '@timestamp'], + sort: [{ '@timestamp': 'desc' }], + }, }, }, }, + latest: { + top_hits: { + size: 1, + _source: ['monitor.status'], + sort: [{ '@timestamp': 'desc' }], + }, + }, }, }, [lastRefresh, monitorId, monitorIdArg, dateRangeStart, dateRangeEnd, selectedLocation?.label], diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors.ts index 6f370aea0554f..4ba62931029d8 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors.ts @@ -77,16 +77,14 @@ export function useInlineErrors({ const { data } = useEsSearch( { index: doFetch ? SYNTHETICS_INDEX_PATTERN : '', - body: { - size: 1000, - query: { - bool: { - filter: getInlineErrorFilters(), - }, + size: 1000, + query: { + bool: { + filter: getInlineErrorFilters(), }, - collapse: { field: 'monitor.id' }, - sort: sortFieldMap[sortField] ? [{ [sortFieldMap[sortField]]: sortOrder }] : undefined, }, + collapse: { field: 'monitor.id' }, + sort: sortFieldMap[sortField] ? [{ [sortFieldMap[sortField]]: sortOrder }] : undefined, }, [syntheticsMonitors, lastRefresh, doFetch, sortField, sortOrder], { name: 'getInvalidMonitors' } diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors_count.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors_count.ts index f91d6d562855a..6e5a68b7ceb6a 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors_count.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/monitors_page/hooks/use_inline_errors_count.ts @@ -21,17 +21,15 @@ export function useInlineErrorsCount() { const { data, loading } = useEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - query: { - bool: { - filter: getInlineErrorFilters(), - }, + size: 0, + query: { + bool: { + filter: getInlineErrorFilters(), }, - aggs: { - total: { - cardinality: { field: 'monitor.id' }, - }, + }, + aggs: { + total: { + cardinality: { field: 'monitor.id' }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings.ts index 129fd36288f5b..b18cfa820d4a6 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings.ts @@ -55,62 +55,60 @@ export const useNetworkTimings = (checkGroupIdArg?: string, stepIndexArg?: numbe const { data } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - runtime_mappings: runTimeMappings, + size: 0, + runtime_mappings: runTimeMappings, - query: { - bool: { - filter: [ - { - term: { - 'synthetics.type': 'journey/network_info', - }, + query: { + bool: { + filter: [ + { + term: { + 'synthetics.type': 'journey/network_info', }, - ...useStepFilters(checkGroupId, stepIndex), - ], - }, - }, - aggs: { - dns: { - sum: { - field: SYNTHETICS_DNS_TIMINGS, }, + ...useStepFilters(checkGroupId, stepIndex), + ], + }, + }, + aggs: { + dns: { + sum: { + field: SYNTHETICS_DNS_TIMINGS, }, - tls: { - sum: { - field: SYNTHETICS_SSL_TIMINGS, - }, + }, + tls: { + sum: { + field: SYNTHETICS_SSL_TIMINGS, }, - blocked: { - sum: { - field: SYNTHETICS_BLOCKED_TIMINGS, - }, + }, + blocked: { + sum: { + field: SYNTHETICS_BLOCKED_TIMINGS, }, - connect: { - sum: { - field: SYNTHETICS_CONNECT_TIMINGS, - }, + }, + connect: { + sum: { + field: SYNTHETICS_CONNECT_TIMINGS, }, - receive: { - sum: { - field: SYNTHETICS_RECEIVE_TIMINGS, - }, + }, + receive: { + sum: { + field: SYNTHETICS_RECEIVE_TIMINGS, }, - send: { - sum: { - field: SYNTHETICS_SEND_TIMINGS, - }, + }, + send: { + sum: { + field: SYNTHETICS_SEND_TIMINGS, }, - wait: { - sum: { - field: SYNTHETICS_WAIT_TIMINGS, - }, + }, + wait: { + sum: { + field: SYNTHETICS_WAIT_TIMINGS, }, - total: { - sum: { - field: SYNTHETICS_TOTAL_TIMINGS, - }, + }, + total: { + sum: { + field: SYNTHETICS_TOTAL_TIMINGS, }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings_prev.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings_prev.ts index 6eeddcf360a14..e964e355f2256 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings_prev.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_network_timings_prev.ts @@ -67,91 +67,89 @@ export const useNetworkTimingsPrevious24Hours = ( const { data, loading } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - runtime_mappings: runTimeMappings, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - lte: moment(timestamp).toISOString(), - gte: moment(timestamp).subtract(24, 'hours').toISOString(), - }, + size: 0, + runtime_mappings: runTimeMappings, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + lte: moment(timestamp).toISOString(), + gte: moment(timestamp).subtract(24, 'hours').toISOString(), }, }, - { - term: { - 'synthetics.type': 'journey/network_info', - }, + }, + { + term: { + 'synthetics.type': 'journey/network_info', }, - { - term: { - 'synthetics.step.index': stepIndex, - }, + }, + { + term: { + 'synthetics.step.index': stepIndex, }, - { - term: { - config_id: configId, - }, + }, + { + term: { + config_id: configId, }, - ], - must_not: [ - { - term: { - 'monitor.check_group': checkGroupId, - }, + }, + ], + must_not: [ + { + term: { + 'monitor.check_group': checkGroupId, }, - ], - }, - }, - aggs: { - testRuns: { - terms: { - field: 'monitor.check_group', - size: 10000, }, - aggs: { - dns: { - sum: { - field: SYNTHETICS_DNS_TIMINGS, - }, + ], + }, + }, + aggs: { + testRuns: { + terms: { + field: 'monitor.check_group', + size: 10000, + }, + aggs: { + dns: { + sum: { + field: SYNTHETICS_DNS_TIMINGS, }, - ssl: { - sum: { - field: SYNTHETICS_SSL_TIMINGS, - }, + }, + ssl: { + sum: { + field: SYNTHETICS_SSL_TIMINGS, }, - blocked: { - sum: { - field: SYNTHETICS_BLOCKED_TIMINGS, - }, + }, + blocked: { + sum: { + field: SYNTHETICS_BLOCKED_TIMINGS, }, - connect: { - sum: { - field: SYNTHETICS_CONNECT_TIMINGS, - }, + }, + connect: { + sum: { + field: SYNTHETICS_CONNECT_TIMINGS, }, - receive: { - sum: { - field: SYNTHETICS_RECEIVE_TIMINGS, - }, + }, + receive: { + sum: { + field: SYNTHETICS_RECEIVE_TIMINGS, }, - send: { - sum: { - field: SYNTHETICS_SEND_TIMINGS, - }, + }, + send: { + sum: { + field: SYNTHETICS_SEND_TIMINGS, }, - wait: { - sum: { - field: SYNTHETICS_WAIT_TIMINGS, - }, + }, + wait: { + sum: { + field: SYNTHETICS_WAIT_TIMINGS, }, - total: { - sum: { - field: SYNTHETICS_TOTAL_TIMINGS, - }, + }, + total: { + sum: { + field: SYNTHETICS_TOTAL_TIMINGS, }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_prev_object_metrics.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_prev_object_metrics.ts index 1a5d31415decb..4061e35b5dc95 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_prev_object_metrics.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_prev_object_metrics.ts @@ -36,83 +36,81 @@ export const usePreviousObjectMetrics = () => { const { data: prevObjectMetrics } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - track_total_hits: false, - sort: [ - { - '@timestamp': { - order: 'desc', - }, - }, - ], - size: 0, - runtime_mappings: { - 'synthetics.payload.transfer_size': { - type: 'long', + track_total_hits: false, + sort: [ + { + '@timestamp': { + order: 'desc', }, }, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - lte: timestamp ?? 'now', - gte: moment(timestamp).subtract(1, 'day').toISOString(), - }, + ], + size: 0, + runtime_mappings: { + 'synthetics.payload.transfer_size': { + type: 'long', + }, + }, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + lte: timestamp ?? 'now', + gte: moment(timestamp).subtract(1, 'day').toISOString(), }, }, - { - term: { - config_id: monitorId, - }, + }, + { + term: { + config_id: monitorId, }, - { - term: { - 'synthetics.type': 'journey/network_info', - }, + }, + { + term: { + 'synthetics.type': 'journey/network_info', }, - { - term: { - 'synthetics.step.index': stepIndex, - }, + }, + { + term: { + 'synthetics.step.index': stepIndex, }, - { - range: { - '@timestamp': { - gte: 'now-24h/h', - lte: 'now', - }, + }, + { + range: { + '@timestamp': { + gte: 'now-24h/h', + lte: 'now', }, }, - ], - must_not: [ - { - term: { - 'monitor.check_group': { - value: checkGroupId, - }, + }, + ], + must_not: [ + { + term: { + 'monitor.check_group': { + value: checkGroupId, }, }, - ], + }, + ], + }, + }, + aggs: { + testRuns: { + cardinality: { + field: 'monitor.check_group', }, }, - aggs: { - testRuns: { - cardinality: { - field: 'monitor.check_group', - }, + objectCounts: { + terms: { + field: 'http.response.mime_type', + size: 500, }, - objectCounts: { - terms: { - field: 'http.response.mime_type', - size: 500, - }, - aggs: { - weight: { - sum: { - field: 'synthetics.payload.transfer_size', - }, + aggs: { + weight: { + sum: { + field: 'synthetics.payload.transfer_size', }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_metrics.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_metrics.ts index fba2917c6ece2..eebe42515b1e7 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_metrics.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_metrics.ts @@ -39,54 +39,52 @@ export const useStepMetrics = (step?: JourneyStep) => { const { data } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - 'synthetics.type': ['step/metrics', 'step/end'], - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + 'synthetics.type': ['step/metrics', 'step/end'], }, - { - term: { - 'monitor.check_group': checkGroupId, - }, + }, + { + term: { + 'monitor.check_group': checkGroupId, }, - { - term: { - 'synthetics.step.index': Number(stepIndex), - }, + }, + { + term: { + 'synthetics.step.index': Number(stepIndex), }, - ], - }, - }, - aggs: { - fcp: { - sum: { - field: SYNTHETICS_FCP, }, + ], + }, + }, + aggs: { + fcp: { + sum: { + field: SYNTHETICS_FCP, }, - lcp: { - sum: { - field: SYNTHETICS_LCP, - }, + }, + lcp: { + sum: { + field: SYNTHETICS_LCP, }, - cls: { - sum: { - field: SYNTHETICS_CLS, - }, + }, + cls: { + sum: { + field: SYNTHETICS_CLS, }, - dcl: { - sum: { - field: SYNTHETICS_DCL, - }, + }, + dcl: { + sum: { + field: SYNTHETICS_DCL, }, - totalDuration: { - sum: { - field: SYNTHETICS_STEP_DURATION, - }, + }, + totalDuration: { + sum: { + field: SYNTHETICS_STEP_DURATION, }, }, }, @@ -98,39 +96,37 @@ export const useStepMetrics = (step?: JourneyStep) => { const { data: transferData } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - runtime_mappings: { - 'synthetics.payload.transfer_size': { - type: 'double', - }, + size: 0, + runtime_mappings: { + 'synthetics.payload.transfer_size': { + type: 'double', }, - query: { - bool: { - filter: [ - { - term: { - 'synthetics.type': 'journey/network_info', - }, + }, + query: { + bool: { + filter: [ + { + term: { + 'synthetics.type': 'journey/network_info', }, - { - term: { - 'monitor.check_group': checkGroupId, - }, + }, + { + term: { + 'monitor.check_group': checkGroupId, }, - { - term: { - 'synthetics.step.index': Number(stepIndex), - }, + }, + { + term: { + 'synthetics.step.index': Number(stepIndex), }, - ], - }, - }, - aggs: { - transferSize: { - sum: { - field: 'synthetics.payload.transfer_size', }, + ], + }, + }, + aggs: { + transferSize: { + sum: { + field: 'synthetics.payload.transfer_size', }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_prev_metrics.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_prev_metrics.ts index 9940620f7cc17..2758584066f76 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_prev_metrics.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/hooks/use_step_prev_metrics.ts @@ -44,68 +44,66 @@ export const useStepPrevMetrics = (step?: JourneyStep) => { const { data, loading } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - query: { - bool: { - filter: [ - { - terms: { - 'synthetics.type': ['step/metrics', 'step/end'], - }, + size: 0, + query: { + bool: { + filter: [ + { + terms: { + 'synthetics.type': ['step/metrics', 'step/end'], }, - { - term: { - 'synthetics.step.index': Number(stepIndex), - }, + }, + { + term: { + 'synthetics.step.index': Number(stepIndex), }, - { - term: { - config_id: monitorId, - }, + }, + { + term: { + config_id: monitorId, }, - { - range: { - '@timestamp': { - lte: 'now', - gte: 'now-24h/h', - }, + }, + { + range: { + '@timestamp': { + lte: 'now', + gte: 'now-24h/h', }, }, - ], - }, - }, - aggs: { - testRuns: { - terms: { - field: 'monitor.check_group', - size: 10000, }, - aggs: { - fcp: { - sum: { - field: SYNTHETICS_FCP, - }, + ], + }, + }, + aggs: { + testRuns: { + terms: { + field: 'monitor.check_group', + size: 10000, + }, + aggs: { + fcp: { + sum: { + field: SYNTHETICS_FCP, }, - lcp: { - sum: { - field: SYNTHETICS_LCP, - }, + }, + lcp: { + sum: { + field: SYNTHETICS_LCP, }, - cls: { - sum: { - field: SYNTHETICS_CLS, - }, + }, + cls: { + sum: { + field: SYNTHETICS_CLS, }, - dcl: { - sum: { - field: SYNTHETICS_DCL, - }, + }, + dcl: { + sum: { + field: SYNTHETICS_DCL, }, - stepDuration: { - sum: { - field: SYNTHETICS_STEP_DURATION, - }, + }, + stepDuration: { + sum: { + field: SYNTHETICS_STEP_DURATION, }, }, }, @@ -118,56 +116,54 @@ export const useStepPrevMetrics = (step?: JourneyStep) => { const { data: transferData } = useReduxEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - runtime_mappings: { - 'synthetics.payload.transfer_size': { - type: 'double', - }, - 'synthetics.payload.resource_size': { - type: 'double', - }, + size: 0, + runtime_mappings: { + 'synthetics.payload.transfer_size': { + type: 'double', }, - query: { - bool: { - filter: [ - { - term: { - 'synthetics.type': 'journey/network_info', - }, + 'synthetics.payload.resource_size': { + type: 'double', + }, + }, + query: { + bool: { + filter: [ + { + term: { + 'synthetics.type': 'journey/network_info', }, - { - term: { - 'synthetics.step.index': Number(stepIndex), - }, + }, + { + term: { + 'synthetics.step.index': Number(stepIndex), }, - { - term: { - config_id: monitorId, - }, + }, + { + term: { + config_id: monitorId, }, - { - range: { - '@timestamp': { - lte: 'now', - gte: 'now-24h/h', - }, + }, + { + range: { + '@timestamp': { + lte: 'now', + gte: 'now-24h/h', }, }, - ], - }, - }, - aggs: { - testRuns: { - terms: { - field: 'monitor.check_group', - size: 10000, }, - aggs: { - transferSize: { - sum: { - field: 'synthetics.payload.transfer_size', - }, + ], + }, + }, + aggs: { + testRuns: { + terms: { + field: 'monitor.check_group', + size: 10000, + }, + aggs: { + transferSize: { + sum: { + field: 'synthetics.payload.transfer_size', }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.test.tsx b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.test.tsx index 743dfa9ff046f..32a0d8865525f 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.test.tsx +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.test.tsx @@ -54,32 +54,30 @@ describe('useStepWaterfallMetrics', () => { expect(searchHook).toHaveBeenCalledWith( { - body: { - _source: false, - fields: ['browser.*'], - query: { - bool: { - filter: [ - { - term: { - 'synthetics.step.index': 1, - }, + _source: false, + fields: ['browser.*'], + query: { + bool: { + filter: [ + { + term: { + 'synthetics.step.index': 1, }, - { - term: { - 'monitor.check_group': '44D-444FFF-444-FFF-3333', - }, + }, + { + term: { + 'monitor.check_group': '44D-444FFF-444-FFF-3333', }, - { - term: { - 'synthetics.type': 'step/metrics', - }, + }, + { + term: { + 'synthetics.type': 'step/metrics', }, - ], - }, + }, + ], }, - size: 1000, }, + size: 1000, index: SYNTHETICS_INDEX_PATTERN, }, ['44D-444FFF-444-FFF-3333', true], diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.ts index cc7c72ec33243..ffa9317025221 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/step_details_page/step_waterfall_chart/use_step_waterfall_metrics.ts @@ -24,32 +24,30 @@ export const useStepWaterfallMetrics = ({ checkGroup, hasNavigationRequest, step hasNavigationRequest ? createEsParams({ index: SYNTHETICS_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - { - term: { - 'synthetics.step.index': stepIndex, - }, + query: { + bool: { + filter: [ + { + term: { + 'synthetics.step.index': stepIndex, }, - { - term: { - 'monitor.check_group': checkGroup, - }, + }, + { + term: { + 'monitor.check_group': checkGroup, }, - { - term: { - 'synthetics.type': 'step/metrics', - }, + }, + { + term: { + 'synthetics.type': 'step/metrics', }, - ], - }, + }, + ], }, - fields: ['browser.*'], - size: 1000, - _source: false, }, + fields: ['browser.*'], + size: 1000, + _source: false, }) : {}, [checkGroup, hasNavigationRequest], diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_browser_run_once_monitors.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_browser_run_once_monitors.ts index c5b11dc272233..c0d4dfd0bd4dd 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_browser_run_once_monitors.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_browser_run_once_monitors.ts @@ -32,28 +32,26 @@ export const useBrowserEsResults = ({ return useEsSearch( createEsParams({ index: SYNTHETICS_INDEX_PATTERN, - body: { - sort: [ - { - '@timestamp': 'desc', - }, - ], - query: { - bool: { - filter: [ - { - terms: { - 'synthetics.type': ['heartbeat/summary', 'journey/start'], - }, + sort: [ + { + '@timestamp': 'desc', + }, + ], + query: { + bool: { + filter: [ + { + terms: { + 'synthetics.type': ['heartbeat/summary', 'journey/start'], }, + }, - { - term: { - test_run_id: testRunId, - }, + { + term: { + test_run_id: testRunId, }, - ], - }, + }, + ], }, }, size: 1000, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_simple_run_once_monitors.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_simple_run_once_monitors.ts index 4cc61d61688f4..acc7c32b898f3 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_simple_run_once_monitors.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/components/test_now_mode/hooks/use_simple_run_once_monitors.ts @@ -27,23 +27,21 @@ export const useSimpleRunOnceMonitors = ({ const { data, loading } = useEsSearch( createEsParams({ index: SYNTHETICS_INDEX_PATTERN, - body: { - sort: [ - { - '@timestamp': 'desc', - }, - ], - query: { - bool: { - filter: [ - FINAL_SUMMARY_FILTER, - { - term: { - test_run_id: testRunId, - }, + sort: [ + { + '@timestamp': 'desc', + }, + ], + query: { + bool: { + filter: [ + FINAL_SUMMARY_FILTER, + { + term: { + test_run_id: testRunId, }, - ], - }, + }, + ], }, }, size: 1000, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_monitor_detail.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_monitor_detail.ts index 1a15cb3549fcc..2a17115158f9d 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_monitor_detail.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_monitor_detail.ts @@ -16,31 +16,29 @@ export const useMonitorDetail = ( ): { data?: Ping; loading?: boolean } => { const params = { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 1, - query: { - bool: { - filter: [ - { - term: { - config_id: configId, - }, + size: 1, + query: { + bool: { + filter: [ + { + term: { + config_id: configId, }, - { - term: { - 'observer.geo.name': location, - }, + }, + { + term: { + 'observer.geo.name': location, }, - { - exists: { - field: 'summary', - }, + }, + { + exists: { + field: 'summary', }, - ], - }, + }, + ], }, - sort: [{ '@timestamp': 'desc' }], }, + sort: [{ '@timestamp': 'desc' as const }], }; const { data: result, loading } = useEsSearch( params, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_redux_es_search.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_redux_es_search.ts index 0f8a281723f03..5eb9f0bd7aafc 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_redux_es_search.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_redux_es_search.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ESSearchResponse } from '@kbn/es-types'; import { IInspectorInfo } from '@kbn/data-plugin/common'; import { useDispatch, useSelector } from 'react-redux'; diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_status_by_location.tsx b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_status_by_location.tsx index f37c087a045d7..dff9d89712284 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_status_by_location.tsx +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/hooks/use_status_by_location.tsx @@ -35,34 +35,32 @@ export function useStatusByLocation({ const { data, loading } = useEsSearch( { index: SYNTHETICS_INDEX_PATTERN, - body: { - size: 0, - query: { - bool: { - filter: [ - FINAL_SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - { - term: { - config_id: configId, - }, + size: 0, + query: { + bool: { + filter: [ + FINAL_SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + { + term: { + config_id: configId, }, - ], - }, - }, - sort: [{ '@timestamp': 'desc' }], - aggs: { - locations: { - terms: { - field: 'observer.geo.name', - missing: UNNAMED_LOCATION, - size: 1000, }, - aggs: { - summary: { - top_hits: { - size: 1, - }, + ], + }, + }, + sort: [{ '@timestamp': 'desc' }], + aggs: { + locations: { + terms: { + field: 'observer.geo.name', + missing: UNNAMED_LOCATION, + size: 1000, + }, + aggs: { + summary: { + top_hits: { + size: 1, }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/actions.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/actions.ts index 93c035bdc8d99..b411a957cc5f5 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/actions.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/actions.ts @@ -5,12 +5,11 @@ * 2.0. */ -import * as esTypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import { ESSearchResponse } from '@kbn/es-types'; +import { ESSearchResponse, ESSearchRequest } from '@kbn/es-types'; import { createAsyncAction } from '../utils/actions'; export interface EsActionPayload { - params: esTypes.SearchRequest; + params: ESSearchRequest; name: string; } diff --git a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/api.ts b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/api.ts index 8c2e14aa3c175..0c294fd6cc6e9 100644 --- a/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/api.ts +++ b/x-pack/solutions/observability/plugins/synthetics/public/apps/synthetics/state/elasticsearch/api.ts @@ -6,7 +6,7 @@ */ import type { IKibanaSearchResponse } from '@kbn/search-types'; import { isRunningResponse } from '@kbn/data-plugin/common'; -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ESSearchResponse } from '@kbn/es-types'; import { FETCH_STATUS } from '@kbn/observability-shared-plugin/public'; import { getInspectResponse } from '@kbn/observability-shared-plugin/common'; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/filter_monitors.ts b/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/filter_monitors.ts index 99309c7435423..065bc4d422a10 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/filter_monitors.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/filter_monitors.ts @@ -30,34 +30,32 @@ export async function queryFilterMonitors({ const filters = toElasticsearchQuery(fromKueryExpression(ruleParams.kqlQuery)); const { body: result } = await esClient.search( { - body: { - size: 0, - query: { - bool: { - filter: [ - FINAL_SUMMARY_FILTER, - getRangeFilter({ from: 'now-24h/m', to: 'now/m' }), - getTimeSpanFilter(), - { - term: { - 'meta.space_id': spaceId, - }, + size: 0, + query: { + bool: { + filter: [ + FINAL_SUMMARY_FILTER, + getRangeFilter({ from: 'now-24h/m', to: 'now/m' }), + getTimeSpanFilter(), + { + term: { + 'meta.space_id': spaceId, }, - { - bool: { - should: filters, - }, + }, + { + bool: { + should: filters, }, - ...getFilters(ruleParams), - ], - }, - }, - aggs: { - ids: { - terms: { - size: 10000, - field: 'config_id', }, + ...getFilters(ruleParams), + ], + }, + }, + aggs: { + ids: { + terms: { + size: 10000, + field: 'config_id', }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/query_monitor_status_alert.ts b/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/query_monitor_status_alert.ts index c09bbb7e7df8e..f3acedbec16c8 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/query_monitor_status_alert.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/status_rule/queries/query_monitor_status_alert.ts @@ -7,7 +7,7 @@ import pMap from 'p-map'; import times from 'lodash/times'; -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { intersection } from 'lodash'; import { AlertStatusMetaData } from '../../../../common/runtime_types/alert_rules/common'; import { @@ -69,56 +69,54 @@ export async function queryMonitorStatusAlert({ async (i) => { const idsToQuery = (monitorQueryIds as string[]).slice(i * idSize, i * idSize + idSize); const params = createEsParams({ - body: { - size: 0, - query: { - bool: { - filter: [ - ...(includeRetests ? [SUMMARY_FILTER] : [FINAL_SUMMARY_FILTER]), - getRangeFilter({ from: range.from, to: range.to }), - { - terms: { - 'monitor.id': idsToQuery, - }, + size: 0, + query: { + bool: { + filter: [ + ...(includeRetests ? [SUMMARY_FILTER] : [FINAL_SUMMARY_FILTER]), + getRangeFilter({ from: range.from, to: range.to }), + { + terms: { + 'monitor.id': idsToQuery, }, - ] as QueryDslQueryContainer[], - }, - }, - aggs: { - id: { - terms: { - field: 'monitor.id', - size: idSize, }, - aggs: { - location: { - terms: { - field: 'observer.name', - size: monitorLocationIds.length || 100, - }, - aggs: { - downChecks: { - filter: { - range: { - 'summary.down': { - gte: '1', - }, + ] as QueryDslQueryContainer[], + }, + }, + aggs: { + id: { + terms: { + field: 'monitor.id', + size: idSize, + }, + aggs: { + location: { + terms: { + field: 'observer.name', + size: monitorLocationIds.length || 100, + }, + aggs: { + downChecks: { + filter: { + range: { + 'summary.down': { + gte: '1', }, }, }, - totalChecks: { - top_hits: { - size: numberOfChecks, - sort: [ - { - '@timestamp': { - order: 'desc', - }, + }, + totalChecks: { + top_hits: { + size: numberOfChecks, + sort: [ + { + '@timestamp': { + order: 'desc', }, - ], - _source: { - includes: fields, }, + ], + _source: { + includes: fields, }, }, }, @@ -130,7 +128,7 @@ export async function queryMonitorStatusAlert({ }); if (monitorLocationIds.length > 0) { - params.body.query.bool.filter.push({ + params.query.bool.filter.push({ terms: { 'observer.name': monitorLocationIds, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/tls_rule/tls_rule_executor.ts b/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/tls_rule/tls_rule_executor.ts index b04729492483d..0828e2cf097cb 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/tls_rule/tls_rule_executor.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/alert_rules/tls_rule/tls_rule_executor.ts @@ -171,50 +171,48 @@ export class TLSRuleExecutor { const configIds = certs.map((cert) => cert.configId); const certIds = certs.map((cert) => cert.sha256); const { body } = await this.esClient.search({ - body: { - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: 'now-1d', - lt: 'now', - }, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: 'now-1d', + lt: 'now', }, }, - { - terms: { - config_id: configIds, - }, + }, + { + terms: { + config_id: configIds, }, - FINAL_SUMMARY_FILTER, - ], - must_not: { - bool: { - filter: [ - { - terms: { - 'tls.server.hash.sha256': certIds, - }, + }, + FINAL_SUMMARY_FILTER, + ], + must_not: { + bool: { + filter: [ + { + terms: { + 'tls.server.hash.sha256': certIds, }, - ], - }, + }, + ], }, }, }, - collapse: { - field: 'config_id', - }, - _source: ['@timestamp', 'monitor', 'url', 'config_id', 'tls'], - sort: [ - { - '@timestamp': { - order: 'desc', - }, - }, - ], }, + collapse: { + field: 'config_id', + }, + _source: ['@timestamp', 'monitor', 'url', 'config_id', 'tls'], + sort: [ + { + '@timestamp': { + order: 'desc', + }, + }, + ], }); return body.hits.hits.map((hit) => hit._source as TLSLatestPing); diff --git a/x-pack/solutions/observability/plugins/synthetics/server/common/pings/monitor_status_heatmap.ts b/x-pack/solutions/observability/plugins/synthetics/server/common/pings/monitor_status_heatmap.ts index cc6015463e9a5..feb8cf7edda27 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/common/pings/monitor_status_heatmap.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/common/pings/monitor_status_heatmap.ts @@ -23,62 +23,60 @@ export async function queryMonitorHeatmap({ intervalInMinutes: number; }) { return syntheticsEsClient.search({ - body: { - size: 0, - query: { - bool: { - filter: [ - { - exists: { - field: 'summary', - }, + size: 0, + query: { + bool: { + filter: [ + { + exists: { + field: 'summary', }, - { - range: { - '@timestamp': { - gte: from, - lte: to, - }, + }, + { + range: { + '@timestamp': { + gte: from, + lte: to, }, }, - { - term: { - 'monitor.id': monitorId, - }, + }, + { + term: { + 'monitor.id': monitorId, }, - { - term: { - 'observer.geo.name': location, - }, + }, + { + term: { + 'observer.geo.name': location, }, - ], + }, + ], + }, + }, + sort: [ + { + '@timestamp': { + order: 'desc', }, }, - sort: [ - { - '@timestamp': { - order: 'desc', - }, + ], + _source: false, + fields: ['@timestamp', 'config_id', 'summary.*', 'error.*', 'observer.geo.name'], + aggs: { + heatmap: { + date_histogram: { + field: '@timestamp', + fixed_interval: `${intervalInMinutes}m`, }, - ], - _source: false, - fields: ['@timestamp', 'config_id', 'summary.*', 'error.*', 'observer.geo.name'], - aggs: { - heatmap: { - date_histogram: { - field: '@timestamp', - fixed_interval: `${intervalInMinutes}m`, - }, - aggs: { - up: { - sum: { - field: 'summary.up', - }, + aggs: { + up: { + sum: { + field: 'summary.up', }, - down: { - sum: { - field: 'summary.down', - }, + }, + down: { + sum: { + field: 'summary.down', }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/server/lib.test.ts b/x-pack/solutions/observability/plugins/synthetics/server/lib.test.ts index bfb19213c4f43..0dd1e2a167b55 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/lib.test.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/lib.test.ts @@ -93,18 +93,14 @@ describe('SyntheticsEsClient', () => { describe('search', () => { it('should call baseESClient.search with correct parameters', async () => { const mockSearchParams = { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; const result = await syntheticsEsClient.search({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); @@ -128,10 +124,8 @@ describe('SyntheticsEsClient', () => { it('should throw an error if baseESClient.search throws an error', async () => { const mockSearchParams = { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; const mockError = new Error('Search error'); diff --git a/x-pack/solutions/observability/plugins/synthetics/server/lib.ts b/x-pack/solutions/observability/plugins/synthetics/server/lib.ts index 8a703e1c051e8..fad3054142a79 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/lib.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/lib.ts @@ -16,7 +16,7 @@ import { CoreRequestHandlerContext, } from '@kbn/core/server'; import chalk from 'chalk'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ESSearchResponse, InferSearchResponseOf } from '@kbn/es-types'; import { RequestStatus } from '@kbn/inspector-plugin/common'; import { InspectResponse } from '@kbn/observability-plugin/typings/common'; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_certs.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_certs.ts index 2d5ad2f84a79e..d5bfd0336f96c 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_certs.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_certs.ts @@ -30,11 +30,7 @@ const getCertsResults = async ( const searchBody = getCertsRequestBody(requestParams); - const request = { body: searchBody }; - - const { body: result } = await syntheticsEsClient.search({ - body: searchBody, - }); + const { body: result } = await syntheticsEsClient.search(searchBody); return result; }; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_details.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_details.ts index 97b3595761cf8..83953466dd0c5 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_details.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_details.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { createEsParams, SyntheticsEsClient } from '../lib'; import { JourneyStep, Ping, SyntheticsJourneyApiResponse } from '../../common/runtime_types'; @@ -22,25 +22,23 @@ export const getJourneyDetails = async ({ syntheticsEsClient: SyntheticsEsClient; }): Promise => { const params = createEsParams({ - body: { - query: { - bool: { - filter: [ - { - term: { - 'monitor.check_group': checkGroup, - }, + query: { + bool: { + filter: [ + { + term: { + 'monitor.check_group': checkGroup, }, - { - terms: { - 'synthetics.type': ['journey/start', 'heartbeat/summary'], - }, + }, + { + terms: { + 'synthetics.type': ['journey/start', 'heartbeat/summary'], }, - ], - }, + }, + ], }, - size: 2, }, + size: 2, }); const { body: thisJourney } = await syntheticsEsClient.search( @@ -62,84 +60,78 @@ export const getJourneyDetails = async ({ if (journeySource && foundJourney) { const baseSiblingParams = createEsParams({ - body: { - query: { - bool: { - must_not: [ - { - term: { - 'monitor.check_group': { - value: journeySource.monitor.check_group, - }, + query: { + bool: { + must_not: [ + { + term: { + 'monitor.check_group': { + value: journeySource.monitor.check_group, }, }, - ], - filter: [ - { - term: { - 'monitor.id': journeySource.monitor.id, - }, + }, + ], + filter: [ + { + term: { + 'monitor.id': journeySource.monitor.id, }, - { - term: { - 'observer.geo.name': journeySource.observer?.geo?.name, - }, + }, + { + term: { + 'observer.geo.name': journeySource.observer?.geo?.name, }, - { - terms: { - 'synthetics.type': ['journey/start', 'heartbeat/summary'], - }, + }, + { + terms: { + 'synthetics.type': ['journey/start', 'heartbeat/summary'], }, - ] as QueryDslQueryContainer[], - }, + }, + ] as QueryDslQueryContainer[], }, - _source: ['@timestamp', 'monitor.check_group'], - size: 1, }, + _source: ['@timestamp', 'monitor.check_group'], + size: 1, }); const previousParams = createEsParams({ - body: { - ...baseSiblingParams.body, - query: { - bool: { - must_not: baseSiblingParams.body.query.bool.must_not, - filter: [ - ...baseSiblingParams.body.query.bool.filter, - { - range: { - '@timestamp': { - lt: journeySource['@timestamp'], - }, + ...baseSiblingParams, + query: { + bool: { + must_not: baseSiblingParams.query.bool.must_not, + filter: [ + ...baseSiblingParams.query.bool.filter, + { + range: { + '@timestamp': { + lt: journeySource['@timestamp'], }, }, - ], - }, + }, + ], }, - sort: [{ '@timestamp': { order: 'desc' as const } }], }, + sort: [{ '@timestamp': { order: 'desc' as const } }], }); const nextParams = createEsParams({ - body: { - ...baseSiblingParams.body, - query: { - bool: { - must_not: baseSiblingParams.body.query.bool.must_not, - filter: [ - ...baseSiblingParams.body.query.bool.filter, - { - range: { - '@timestamp': { - gt: journeySource['@timestamp'], - }, + ...baseSiblingParams, + query: { + bool: { + must_not: baseSiblingParams.query.bool.must_not, + filter: [ + ...baseSiblingParams.query.bool.filter, + { + range: { + '@timestamp': { + gt: journeySource['@timestamp'], }, }, - ], - }, + }, + ], }, - sort: [{ '@timestamp': { order: 'asc' as const } }], }, + sort: [{ '@timestamp': { order: 'asc' as const } }], }); const [previousJourneyPromise, nextJourneyPromise] = await Promise.all([ diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_failed_steps.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_failed_steps.ts index bde1a970e21f9..d9a87378f4105 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_failed_steps.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_failed_steps.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SyntheticsEsClient } from '../lib'; import { asMutableArray } from '../../common/utils/as_mutable_array'; import { JourneyStep } from '../../common/runtime_types/ping/synthetics'; @@ -52,7 +52,7 @@ export const getJourneyFailedSteps = async ({ size: 500, }; - const { body: result } = await syntheticsEsClient.search({ body: params }); + const { body: result } = await syntheticsEsClient.search(params); return result.hits.hits.map(({ _id, _source }) => { const step = Object.assign({ _id }, _source) as JourneyStep; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot.ts index e707b34248c02..41daca19616f3 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SyntheticsEsClient } from '../lib'; import { RefResult, FullScreenshot } from '../../common/runtime_types/ping/synthetics'; @@ -64,7 +64,7 @@ export const getJourneyScreenshot = async ({ }, }; - const result = await syntheticsEsClient.search({ body }); + const result = await syntheticsEsClient.search(body); const screenshotsOrRefs = (result.body.aggregations?.step.image.hits.hits as ResultType[]) ?? null; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot_blocks.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot_blocks.ts index 47767df107c04..4eecae5ddbee2 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot_blocks.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_screenshot_blocks.ts @@ -41,7 +41,7 @@ export const getJourneyScreenshotBlocks = async ({ size: 1000, }; - const fetchScreenshotBlocksResult = await syntheticsEsClient.search({ body }); + const fetchScreenshotBlocksResult = await syntheticsEsClient.search(body); return (fetchScreenshotBlocksResult.body.hits.hits as ScreenshotBlockResultType[]).map( ({ _id, _source }) => ({ diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.test.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.test.ts index bd1ee592634c4..f2f456773cce6 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.test.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.test.ts @@ -87,7 +87,7 @@ describe('getJourneySteps request module', () => { const call: any = mockEsClient.search.mock.calls[0][0]; // check that default `synthetics.type` value is supplied, - expect(call.body.query.bool.filter[0]).toMatchInlineSnapshot(` + expect(call.query.bool.filter[0]).toMatchInlineSnapshot(` Object { "terms": Object { "synthetics.type": Array [ @@ -102,7 +102,7 @@ describe('getJourneySteps request module', () => { `); // given check group is used for the terms filter - expect(call.body.query.bool.filter[1]).toMatchInlineSnapshot(` + expect(call.query.bool.filter[1]).toMatchInlineSnapshot(` Object { "term": Object { "monitor.check_group": "2bf952dc-64b5-11eb-8b3b-42010a84000d", @@ -111,7 +111,7 @@ describe('getJourneySteps request module', () => { `); // should sort by step index, then timestamp - expect(call.body.sort).toMatchInlineSnapshot(` + expect(call.sort).toMatchInlineSnapshot(` Array [ Object { "synthetics.step.index": Object { @@ -152,7 +152,7 @@ describe('getJourneySteps request module', () => { const call: any = mockEsClient.search.mock.calls[0][0]; // assert that filters for only the provided step types are used - expect(call.body.query.bool.filter[0]).toMatchInlineSnapshot(` + expect(call.query.bool.filter[0]).toMatchInlineSnapshot(` Object { "terms": Object { "synthetics.type": Array [ diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.ts index 0cd964193b2ff..cfbccdb57d6d9 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_journey_steps.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SyntheticsEsClient } from '../lib'; import { asMutableArray } from '../../common/utils/as_mutable_array'; import { JourneyStep } from '../../common/runtime_types/ping/synthetics'; @@ -54,7 +54,7 @@ export const getJourneySteps = async ({ }, size: 500, }; - const { body: result } = await syntheticsEsClient.search({ body: params }, 'getJourneySteps'); + const { body: result } = await syntheticsEsClient.search(params, 'getJourneySteps'); const steps = result.hits.hits.map( ({ _id, _source }) => Object.assign({ _id }, _source) as ResultType diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_last_successful_check.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_last_successful_check.ts index 271ef438fbf65..70abfff4f5b44 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_last_successful_check.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_last_successful_check.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SyntheticsEsClient } from '../lib'; import { Ping } from '../../common/runtime_types/ping'; @@ -19,7 +19,7 @@ export const getLastSuccessfulStepParams = ({ monitorId, timestamp, location, -}: GetStepScreenshotParams): estypes.SearchRequest['body'] => { +}: GetStepScreenshotParams): estypes.SearchRequest => { return { size: 1, sort: [ @@ -94,7 +94,7 @@ export const getLastSuccessfulCheck = async ({ location, }); - const { body: result } = await syntheticsEsClient.search({ body: lastSuccessCheckParams }); + const { body: result } = await syntheticsEsClient.search(lastSuccessCheckParams); if (result.hits.total.value < 1) { return null; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_latest_test_run.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_latest_test_run.ts index 984349c5f20ed..08bf51634f985 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_latest_test_run.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_latest_test_run.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { Ping } from '../../common/runtime_types'; import { SyntheticsEsClient } from '../lib'; import { getRangeFilter, SUMMARY_FILTER } from '../../common/constants/client_defaults'; @@ -24,19 +24,17 @@ export async function getLatestTestRun({ to?: string; }): Promise { const response = await syntheticsEsClient.search({ - body: { - query: { - bool: { - filter: [ - SUMMARY_FILTER, - getRangeFilter({ from, to }), - { term: { 'monitor.id': monitorId } }, - ...(locationLabel ? [{ term: { 'observer.geo.name': locationLabel } }] : []), - ] as QueryDslQueryContainer[], - }, + query: { + bool: { + filter: [ + SUMMARY_FILTER, + getRangeFilter({ from, to }), + { term: { 'monitor.id': monitorId } }, + ...(locationLabel ? [{ term: { 'observer.geo.name': locationLabel } }] : []), + ] as QueryDslQueryContainer[], }, - sort: [{ '@timestamp': { order: 'desc' } }], }, + sort: [{ '@timestamp': { order: 'desc' } }], }); return response.body.hits.hits[0]?._source as Ping | undefined; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.test.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.test.ts index c55fb7a1af4ff..74c74994c46cd 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.test.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.test.ts @@ -188,32 +188,30 @@ describe('getNetworkEvents', () => { Array [ Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "synthetics.type": "journey/network_info", - }, + "index": "synthetics-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "synthetics.type": "journey/network_info", }, - Object { - "term": Object { - "monitor.check_group": "my-fake-group", - }, + }, + Object { + "term": Object { + "monitor.check_group": "my-fake-group", }, - Object { - "term": Object { - "synthetics.step.index": 1, - }, + }, + Object { + "term": Object { + "synthetics.step.index": 1, }, - ], - }, + }, + ], }, - "size": 1000, - "track_total_hits": true, }, - "index": "synthetics-*", + "size": 1000, + "track_total_hits": true, }, Object { "meta": true, diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.ts index 58cafe505fd63..56e835dc26424 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/get_network_events.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SyntheticsEsClient } from '../lib'; import { NetworkEvent } from '../../common/runtime_types'; @@ -47,7 +47,7 @@ export const getNetworkEvents = async ({ size: 1000, }; - const { body: result } = await syntheticsEsClient.search({ body: params }); + const { body: result } = await syntheticsEsClient.search(params); let isWaterfallSupported = false; let hasNavigationRequest = false; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.test.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.test.ts index 2f6a169d1bcc6..ff68ba7a49e44 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.test.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.test.ts @@ -54,7 +54,7 @@ describe('queryPings', () => { expect(mockEsClient.search).toHaveBeenCalledTimes(1); const searchParams = (mockEsClient.search as jest.Mock).mock.calls[0][0]; - expect(searchParams.body.size).toEqual(sizeParam ?? 25); + expect(searchParams.size).toEqual(sizeParam ?? 25); } ); diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.ts index 4ed64eb2d5c8b..9cab1ddc4b67c 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/query_pings.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { +import type { Field, QueryDslFieldAndFormat, QueryDslQueryContainer, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import { GetPingsParams, HttpResponseBody, Ping, PingsResponse } from '../../common/runtime_types'; import { SyntheticsEsClient } from '../lib'; import { SUMMARY_FILTER } from '../../common/constants/client_defaults'; @@ -97,7 +97,7 @@ export async function queryPings( body: { hits: { hits, total }, }, - } = await syntheticsEsClient.search({ body: searchBody }); + } = await syntheticsEsClient.search(searchBody); return { total: total.value, @@ -109,7 +109,7 @@ export async function queryPings( body: { hits: { hits, total }, }, - } = await syntheticsEsClient.search({ body: searchBody }); + } = await syntheticsEsClient.search(searchBody); const pings: Ping[] = hits.map((doc: any) => { const { _id, _source } = doc; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/queries/test_helpers.ts b/x-pack/solutions/observability/plugins/synthetics/server/queries/test_helpers.ts index 92f9bb824d3b8..4fd6f05ac38c6 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/queries/test_helpers.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/queries/test_helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AggregationsAggregate } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsAggregate } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { elasticsearchServiceMock, savedObjectsClientMock } from '@kbn/core/server/mocks'; import { SyntheticsEsClient } from '../lib'; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_status/overview_status_service.ts b/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_status/overview_status_service.ts index 5ff8a870db9de..552f30512d0eb 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_status/overview_status_service.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_status/overview_status_service.ts @@ -6,7 +6,7 @@ */ import moment from 'moment/moment'; -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { SavedObjectsFindResult } from '@kbn/core-saved-objects-api-server'; import { isEmpty } from 'lodash'; import { withApmSpan } from '@kbn/apm-data-access-plugin/server/utils/with_apm_span'; @@ -155,49 +155,47 @@ export class OverviewStatusService { do { const result = await this.routeContext.syntheticsEsClient.search( { - body: { - size: 0, - query: { - bool: { - filter: [ - FINAL_SUMMARY_FILTER, - getRangeFilter({ from: range.from, to: range.to }), - getTimespanFilter({ from: 'now-15m', to: 'now' }), - ...this.getEsDataFilters(), - ] as QueryDslQueryContainer[], - }, + size: 0, + query: { + bool: { + filter: [ + FINAL_SUMMARY_FILTER, + getRangeFilter({ from: range.from, to: range.to }), + getTimespanFilter({ from: 'now-15m', to: 'now' }), + ...this.getEsDataFilters(), + ] as QueryDslQueryContainer[], }, - aggs: { - monitors: { - composite: { - size: SUMMARIES_PAGE_SIZE, - sources: asMutableArray([ - { - monitorId: { - terms: { - field: 'monitor.id', - }, + }, + aggs: { + monitors: { + composite: { + size: SUMMARIES_PAGE_SIZE, + sources: asMutableArray([ + { + monitorId: { + terms: { + field: 'monitor.id', }, }, - { - locationId: { - terms: { - field: 'observer.name', - }, + }, + { + locationId: { + terms: { + field: 'observer.name', }, }, - ] as const), - after: afterKey, - }, - aggs: { - status: { - top_metrics: { - metrics: { - field: 'monitor.status', - }, - sort: { - '@timestamp': 'desc', - }, + }, + ] as const), + after: afterKey, + }, + aggs: { + status: { + top_metrics: { + metrics: { + field: 'monitor.status', + }, + sort: { + '@timestamp': 'desc', }, }, }, diff --git a/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/fetch_trends.ts b/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/fetch_trends.ts index b57c634c1bddd..a27f2cbe1cfd5 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/fetch_trends.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/fetch_trends.ts @@ -10,83 +10,81 @@ import { createEsParams } from '../../lib'; export const getFetchTrendsQuery = (configId: string, locationIds: string[], interval: number) => createEsParams({ - body: { - size: 0, - query: { - bool: { - filter: [ - SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - { - terms: { - 'observer.name': locationIds, - }, + size: 0, + query: { + bool: { + filter: [ + SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + { + terms: { + 'observer.name': locationIds, }, - { - term: { - config_id: configId, - }, + }, + { + term: { + config_id: configId, }, - { - range: { - '@timestamp': { - gte: `now-${interval}m`, - lte: 'now', - }, + }, + { + range: { + '@timestamp': { + gte: `now-${interval}m`, + lte: 'now', }, }, - ], - }, - }, - aggs: { - byId: { - terms: { - field: 'config_id', }, - aggs: { - byLocation: { - terms: { - field: 'observer.name', - }, - aggs: { - last50: { - histogram: { - field: '@timestamp', - interval: interval * 1000, - min_doc_count: 1, - }, - aggs: { - max: { - avg: { - field: 'monitor.duration.us', - }, + ], + }, + }, + aggs: { + byId: { + terms: { + field: 'config_id', + }, + aggs: { + byLocation: { + terms: { + field: 'observer.name', + }, + aggs: { + last50: { + histogram: { + field: '@timestamp', + interval: interval * 1000, + min_doc_count: 1, + }, + aggs: { + max: { + avg: { + field: 'monitor.duration.us', }, }, }, + }, + stats: { stats: { - stats: { - field: 'monitor.duration.us', - }, + field: 'monitor.duration.us', }, - median: { - percentiles: { - field: 'monitor.duration.us', - percents: [50], - }, + }, + median: { + percentiles: { + field: 'monitor.duration.us', + percents: [50], }, }, }, }, }, }, - _source: false, - sort: [ - { - '@timestamp': 'desc', - }, - ], - fields: ['monitor.duration.us'], }, + _source: false, + sort: [ + { + '@timestamp': 'desc', + }, + ], + fields: ['monitor.duration.us'], }); export type TrendsQuery = ReturnType; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/overview_trends.ts b/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/overview_trends.ts index 66be7171b2fe4..d2acae1d94f0d 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/overview_trends.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/routes/overview_trends/overview_trends.ts @@ -25,8 +25,8 @@ export async function fetchTrends( } > ): Promise { - const requests = Object.keys(configs).map( - (key) => getFetchTrendsQuery(key, configs[key].locations, configs[key].interval).body + const requests = Object.keys(configs).map((key) => + getFetchTrendsQuery(key, configs[key].locations, configs[key].interval) ); const results = await esClient.msearch(requests); diff --git a/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/authentication/check_has_privilege.ts b/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/authentication/check_has_privilege.ts index 09fa498d12cda..bcb8fc2668556 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/authentication/check_has_privilege.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/authentication/check_has_privilege.ts @@ -19,22 +19,18 @@ export const checkHasPrivileges = ( return server.coreStart.elasticsearch.client .asScoped(getFakeKibanaRequest({ id: apiKey.id, api_key: apiKey.apiKey })) .asCurrentUser.security.hasPrivileges({ - body: { - index, - cluster, - }, + index, + cluster, }); }; export const checkIndicesReadPrivileges = (syntheticsEsClient: SyntheticsEsClient) => { return syntheticsEsClient.baseESClient.security.hasPrivileges({ - body: { - index: [ - { - names: [syntheticsIndex], - privileges: ['read'] as SecurityIndexPrivilege[], - }, - ], - }, + index: [ + { + names: [syntheticsIndex], + privileges: ['read'] as SecurityIndexPrivilege[], + }, + ], }); }; diff --git a/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_api_key.ts b/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_api_key.ts index b43f1356b098c..3490af3b646ea 100644 --- a/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_api_key.ts +++ b/x-pack/solutions/observability/plugins/synthetics/server/synthetics_service/get_api_key.ts @@ -215,10 +215,8 @@ const hasEnablePermissions = async ({ const { cluster: clusterPrivs, indices: index } = getServiceApiKeyPrivileges(isElasticsearchServerless); const hasPrivileges = await syntheticsEsClient.baseESClient.security.hasPrivileges({ - body: { - cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key', ...clusterPrivs], - index, - }, + cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key', ...clusterPrivs], + index, }); const { cluster } = hasPrivileges; diff --git a/x-pack/solutions/observability/plugins/uptime/common/requests/get_certs_request_body.ts b/x-pack/solutions/observability/plugins/uptime/common/requests/get_certs_request_body.ts index 84b65d9d54915..a72e391f104bb 100644 --- a/x-pack/solutions/observability/plugins/uptime/common/requests/get_certs_request_body.ts +++ b/x-pack/solutions/observability/plugins/uptime/common/requests/get_certs_request_body.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import DateMath from '@kbn/datemath'; import { EXCLUDE_RUN_ONCE_FILTER, SUMMARY_FILTER } from '../constants/client_defaults'; import { CertResult, GetCertsParams, Ping } from '../runtime_types'; @@ -47,129 +47,125 @@ export const getCertsRequestBody = ({ const sort = SortFields[sortBy as keyof typeof SortFields]; const searchRequest = createEsQuery({ - body: { - from: pageIndex * size, - size, - sort: asMutableArray([ - { - [sort]: { - order: direction, - }, + from: pageIndex * size, + size, + sort: asMutableArray([ + { + [sort]: { + order: direction, }, - ]) as estypes.SortCombinations[], - query: { - bool: { - ...(search - ? { - minimum_should_match: 1, - should: [ - { - multi_match: { - query: escape(search), - type: 'phrase_prefix' as const, - fields: [ - 'monitor.id.text', - 'monitor.name.text', - 'url.full.text', - 'tls.server.x509.subject.common_name.text', - 'tls.server.x509.issuer.common_name.text', - ], - }, + }, + ]) as estypes.SortCombinations[], + query: { + bool: { + ...(search + ? { + minimum_should_match: 1, + should: [ + { + multi_match: { + query: escape(search), + type: 'phrase_prefix' as const, + fields: [ + 'monitor.id.text', + 'monitor.name.text', + 'url.full.text', + 'tls.server.x509.subject.common_name.text', + 'tls.server.x509.issuer.common_name.text', + ], }, - ], - } - : {}), - filter: [ - SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - ...(filters ? [filters] : []), - ...(monitorIds && monitorIds.length > 0 - ? [{ terms: { 'monitor.id': monitorIds } }] - : []), - { - exists: { - field: 'tls.server.hash.sha256', - }, - }, - { - range: { - 'monitor.timespan': { - gte: absoluteDate(from), - lte: absoluteDate(to), }, + ], + } + : {}), + filter: [ + SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + ...(filters ? [filters] : []), + ...(monitorIds && monitorIds.length > 0 ? [{ terms: { 'monitor.id': monitorIds } }] : []), + { + exists: { + field: 'tls.server.hash.sha256', + }, + }, + { + range: { + 'monitor.timespan': { + gte: absoluteDate(from), + lte: absoluteDate(to), }, }, - { - bool: { - // these notValidBefore and notValidAfter should be inside should block, since - // we want to match either of the condition, making ir an OR operation - minimum_should_match: 1, - should: [ - ...(notValidBefore - ? [ - { - range: { - 'tls.certificate_not_valid_before': { - lte: absoluteDate(notValidBefore), - }, + }, + { + bool: { + // these notValidBefore and notValidAfter should be inside should block, since + // we want to match either of the condition, making ir an OR operation + minimum_should_match: 1, + should: [ + ...(notValidBefore + ? [ + { + range: { + 'tls.certificate_not_valid_before': { + lte: absoluteDate(notValidBefore), }, }, - ] - : []), - ...(notValidAfter - ? [ - { - range: { - 'tls.certificate_not_valid_after': { - lte: absoluteDate(notValidAfter), - }, + }, + ] + : []), + ...(notValidAfter + ? [ + { + range: { + 'tls.certificate_not_valid_after': { + lte: absoluteDate(notValidAfter), }, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, - ] as estypes.QueryDslQueryContainer, - }, - }, - _source: [ - 'monitor.id', - 'monitor.name', - 'monitor.type', - 'url.full', - 'observer.geo.name', - 'tls.server.x509.issuer.common_name', - 'tls.server.x509.subject.common_name', - 'tls.server.hash.sha1', - 'tls.server.hash.sha256', - 'tls.server.x509.not_after', - 'tls.server.x509.not_before', - ], - collapse: { - field: 'tls.server.hash.sha256', - inner_hits: { - _source: { - includes: ['monitor.id', 'monitor.name', 'url.full', 'config_id'], }, - collapse: { - field: 'monitor.id', - }, - name: 'monitors', - sort: [{ 'monitor.id': 'asc' as const }], + ] as estypes.QueryDslQueryContainer, + }, + }, + _source: [ + 'monitor.id', + 'monitor.name', + 'monitor.type', + 'url.full', + 'observer.geo.name', + 'tls.server.x509.issuer.common_name', + 'tls.server.x509.subject.common_name', + 'tls.server.hash.sha1', + 'tls.server.hash.sha256', + 'tls.server.x509.not_after', + 'tls.server.x509.not_before', + ], + collapse: { + field: 'tls.server.hash.sha256', + inner_hits: { + _source: { + includes: ['monitor.id', 'monitor.name', 'url.full', 'config_id'], + }, + collapse: { + field: 'monitor.id', }, + name: 'monitors', + sort: [{ 'monitor.id': 'asc' as const }], }, - aggs: { - total: { - cardinality: { - field: 'tls.server.hash.sha256', - }, + }, + aggs: { + total: { + cardinality: { + field: 'tls.server.hash.sha256', }, }, }, }); - return searchRequest.body; + return searchRequest; }; export const processCertsResult = (result: CertificatesResults): CertResult => { diff --git a/x-pack/solutions/observability/plugins/uptime/common/utils/es_search.ts b/x-pack/solutions/observability/plugins/uptime/common/utils/es_search.ts index 6a41b83d19ee0..6a136f3a5d0e7 100644 --- a/x-pack/solutions/observability/plugins/uptime/common/utils/es_search.ts +++ b/x-pack/solutions/observability/plugins/uptime/common/utils/es_search.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export function createEsQuery(params: T): T { return params; diff --git a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/certificates/use_cert_search.ts b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/certificates/use_cert_search.ts index 765d1c3644904..887aee2c66b00 100644 --- a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/certificates/use_cert_search.ts +++ b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/certificates/use_cert_search.ts @@ -45,7 +45,7 @@ export const useCertSearch = ({ const esParams = createEsParams({ index: settings.settings?.heartbeatIndices, - body: searchBody, + ...searchBody, }); const { data: result, loading } = useEsSearch( diff --git a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.test.tsx b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.test.tsx index a8b19dea83839..6b4cd032f390f 100644 --- a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.test.tsx +++ b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.test.tsx @@ -59,32 +59,30 @@ describe('useStepWaterfallMetrics', () => { expect(searchHook).toHaveBeenCalledWith( { - body: { - _source: false, - fields: ['browser.*'], - query: { - bool: { - filter: [ - { - term: { - 'synthetics.step.index': 1, - }, + _source: false, + fields: ['browser.*'], + query: { + bool: { + filter: [ + { + term: { + 'synthetics.step.index': 1, }, - { - term: { - 'monitor.check_group': '44D-444FFF-444-FFF-3333', - }, + }, + { + term: { + 'monitor.check_group': '44D-444FFF-444-FFF-3333', }, - { - term: { - 'synthetics.type': 'step/metrics', - }, + }, + { + term: { + 'synthetics.type': 'step/metrics', }, - ], - }, + }, + ], }, - size: 1000, }, + size: 1000, index: 'heartbeat-*', }, ['heartbeat-*', '44D-444FFF-444-FFF-3333', true], diff --git a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.ts b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.ts index 49f0aa066d52e..74eca490631b8 100644 --- a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.ts +++ b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/monitor/synthetics/step_detail/use_step_waterfall_metrics.ts @@ -29,32 +29,30 @@ export const useStepWaterfallMetrics = ({ checkGroup, hasNavigationRequest, step hasNavigationRequest ? createEsParams({ index: heartbeatIndices!, - body: { - query: { - bool: { - filter: [ - { - term: { - 'synthetics.step.index': stepIndex, - }, + query: { + bool: { + filter: [ + { + term: { + 'synthetics.step.index': stepIndex, }, - { - term: { - 'monitor.check_group': checkGroup, - }, + }, + { + term: { + 'monitor.check_group': checkGroup, }, - { - term: { - 'synthetics.type': 'step/metrics', - }, + }, + { + term: { + 'synthetics.type': 'step/metrics', }, - ], - }, + }, + ], }, - fields: ['browser.*'], - size: 1000, - _source: false, }, + fields: ['browser.*'], + size: 1000, + _source: false, }) : {}, [heartbeatIndices, checkGroup, hasNavigationRequest], diff --git a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/overview/monitor_list/use_monitor_histogram.ts b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/overview/monitor_list/use_monitor_histogram.ts index 0382d1fe5fb00..bfbaeb76553f7 100644 --- a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/overview/monitor_list/use_monitor_histogram.ts +++ b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/overview/monitor_list/use_monitor_histogram.ts @@ -7,7 +7,7 @@ import { useContext } from 'react'; import { useSelector } from 'react-redux'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { useEsSearch } from '@kbn/observability-shared-plugin/public'; import { Histogram, @@ -83,50 +83,48 @@ const getQueryParams = ( const queryParams = { index, - body: { - size: 0, - query: { - bool: { - filter: [ - { - range: { - 'summary.down': { gt: 0 }, - }, + size: 0, + query: { + bool: { + filter: [ + { + range: { + 'summary.down': { gt: 0 }, }, - { - terms: { - 'monitor.id': monitorIds, - }, + }, + { + terms: { + 'monitor.id': monitorIds, }, - { - range: { - '@timestamp': { - gte: dateRangeStart, - lte: dateRangeEnd, - }, + }, + { + range: { + '@timestamp': { + gte: dateRangeStart, + lte: dateRangeEnd, }, }, - ] as estypes.QueryDslQueryContainer, - }, - }, - aggs: { - histogram: { - date_histogram: { - field: '@timestamp', - // 12 seems to be a good size for performance given - // long monitor lists of up to 100 on the overview page - fixed_interval: minInterval + 'ms', }, - aggs: { - by_id: { - terms: { - field: 'monitor.id', - size: Math.max(monitorIds.length, 1), - }, - aggs: { - totalDown: { - sum: { field: 'summary.down' }, - }, + ] as estypes.QueryDslQueryContainer, + }, + }, + aggs: { + histogram: { + date_histogram: { + field: '@timestamp', + // 12 seems to be a good size for performance given + // long monitor lists of up to 100 on the overview page + fixed_interval: minInterval + 'ms', + }, + aggs: { + by_id: { + terms: { + field: 'monitor.id', + size: Math.max(monitorIds.length, 1), + }, + aggs: { + totalDown: { + sum: { field: 'summary.down' }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/synthetics/check_steps/use_std_error_logs.ts b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/synthetics/check_steps/use_std_error_logs.ts index 9510cf454307f..27aff3acb9870 100644 --- a/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/synthetics/check_steps/use_std_error_logs.ts +++ b/x-pack/solutions/observability/plugins/uptime/public/legacy_uptime/components/synthetics/check_steps/use_std_error_logs.ts @@ -21,36 +21,34 @@ export const useStdErrorLogs = ({ const { data, loading } = useEsSearch( createEsParams({ index: !monitorId && !checkGroup ? '' : settings?.heartbeatIndices, - body: { - size: 1000, - query: { - bool: { - filter: [ - { - term: { - 'synthetics.type': 'stderr', - }, + size: 1000, + query: { + bool: { + filter: [ + { + term: { + 'synthetics.type': 'stderr', }, - ...(monitorId - ? [ - { - term: { - 'monitor.id': monitorId, - }, + }, + ...(monitorId + ? [ + { + term: { + 'monitor.id': monitorId, }, - ] - : []), - ...(checkGroup - ? [ - { - term: { - 'monitor.check_group': checkGroup, - }, + }, + ] + : []), + ...(checkGroup + ? [ + { + term: { + 'monitor.check_group': checkGroup, }, - ] - : []), - ], - }, + }, + ] + : []), + ], }, }, }), diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.test.ts index 1dadb58e7c59f..97b5973003df4 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.test.ts @@ -27,18 +27,14 @@ describe('UptimeEsClient', () => { describe('search', () => { it('should call baseESClient.search with correct parameters', async () => { const mockSearchParams = { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; const result = await uptimeEsClient.search({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); @@ -62,10 +58,8 @@ describe('UptimeEsClient', () => { it('should throw an error if baseESClient.search throws an error', async () => { const mockSearchParams = { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; const mockError = new Error('Search error'); @@ -150,18 +144,14 @@ describe('UptimeEsClient', () => { uptimeEsClient = new UptimeEsClient(savedObjectsClient, esClient, { stackVersion: '8.9.0' }); const mockSearchParams = { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; await uptimeEsClient.search({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); @@ -183,18 +173,14 @@ describe('UptimeEsClient', () => { uptimeEsClient = new UptimeEsClient(savedObjectsClient, esClient, { stackVersion: '8.9.0' }); const mockSearchParams = { - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; await uptimeEsClient.search({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); @@ -218,20 +204,16 @@ describe('UptimeEsClient', () => { }); await uptimeEsClient.search({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); expect(esClient.search).toHaveBeenCalledWith( { index: 'heartbeat-*', - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, { meta: true } @@ -242,20 +224,16 @@ describe('UptimeEsClient', () => { }); await uptimeEsClient.search({ - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); expect(esClient.search).toHaveBeenLastCalledWith( { index: 'heartbeat-*', - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, { meta: true } diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.ts index 5b1326bf7a065..e7f713359d156 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/lib.ts @@ -13,7 +13,7 @@ import { SavedObjectsErrorHelpers, } from '@kbn/core/server'; import chalk from 'chalk'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ESSearchResponse } from '@kbn/es-types'; import { RequestStatus } from '@kbn/inspector-plugin/common'; import { InspectResponse } from '@kbn/observability-plugin/typings/common'; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_details.test.ts.snap b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_details.test.ts.snap index ede405a125cc7..47bb3023b5466 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_details.test.ts.snap +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_details.test.ts.snap @@ -3,59 +3,57 @@ exports[`getMonitorDetails getMonitorAlerts should use expected filters for the query 1`] = ` Array [ Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "terms": Object { - "field": "monitor.id", - "size": 1000, - }, + "aggs": Object { + "monitors": Object { + "terms": Object { + "field": "monitor.id", + "size": 1000, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "monitor.id": "fooID", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "monitor.id": "fooID", }, - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match": Object { - "monitor.type": "http", - }, + }, + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match": Object { + "monitor.type": "http", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "url.domain": "www.cnn.com", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "url.domain": "www.cnn.com", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, }, Object { "meta": true, @@ -66,47 +64,45 @@ Array [ exports[`getMonitorDetails getMonitorDetails will provide expected calls 1`] = ` Array [ Object { - "body": Object { - "_source": Array [ - "error", - "@timestamp", - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-15m", - "lte": "now", - }, + "_source": Array [ + "error", + "@timestamp", + ], + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-15m", + "lte": "now", }, }, - Object { - "term": Object { - "monitor.id": "fooID", - }, + }, + Object { + "term": Object { + "monitor.id": "fooID", }, - ], - "must": Array [ - Object { - "exists": Object { - "field": "error", - }, + }, + ], + "must": Array [ + Object { + "exists": Object { + "field": "error", }, - ], - }, - }, - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, + ], }, Object { "meta": true, diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_duration.test.ts.snap b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_duration.test.ts.snap index 712f1f9205cad..b8d87dc027c41 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_duration.test.ts.snap +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/__snapshots__/get_monitor_duration.test.ts.snap @@ -3,73 +3,71 @@ exports[`ElasticsearchMonitorsAdapter getMonitorChartsData will provide expected filters 1`] = ` Array [ Object { - "body": Object { - "aggs": Object { - "timeseries": Object { - "aggs": Object { - "location": Object { - "aggs": Object { - "duration": Object { - "stats": Object { - "field": "monitor.duration.us", - }, + "aggs": Object { + "timeseries": Object { + "aggs": Object { + "location": Object { + "aggs": Object { + "duration": Object { + "stats": Object { + "field": "monitor.duration.us", }, }, - "terms": Object { - "field": "observer.geo.name", - "missing": "Unnamed-location", - }, }, - }, - "auto_date_histogram": Object { - "buckets": 25, - "field": "@timestamp", + "terms": Object { + "field": "observer.geo.name", + "missing": "Unnamed-location", + }, }, }, + "auto_date_histogram": Object { + "buckets": 25, + "field": "@timestamp", + }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-15m", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-15m", + "lte": "now", }, }, - Object { - "term": Object { - "monitor.id": "fooID", - }, + }, + Object { + "term": Object { + "monitor.id": "fooID", }, - Object { - "range": Object { - "monitor.duration.us": Object { - "gt": 0, - }, + }, + Object { + "range": Object { + "monitor.duration.us": Object { + "gt": 0, }, }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, }, Object { "meta": true, diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.test.ts index 07c2a01256864..7c6aa1fed6be3 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.test.ts @@ -137,123 +137,121 @@ describe('getCerts', () => { Array [ Array [ Object { - "body": Object { - "_source": Array [ - "monitor.id", - "monitor.name", - "monitor.type", - "url.full", - "observer.geo.name", - "tls.server.x509.issuer.common_name", - "tls.server.x509.subject.common_name", - "tls.server.hash.sha1", - "tls.server.hash.sha256", - "tls.server.x509.not_after", - "tls.server.x509.not_before", - ], - "aggs": Object { - "total": Object { - "cardinality": Object { - "field": "tls.server.hash.sha256", - }, + "_source": Array [ + "monitor.id", + "monitor.name", + "monitor.type", + "url.full", + "observer.geo.name", + "tls.server.x509.issuer.common_name", + "tls.server.x509.subject.common_name", + "tls.server.hash.sha1", + "tls.server.hash.sha256", + "tls.server.x509.not_after", + "tls.server.x509.not_before", + ], + "aggs": Object { + "total": Object { + "cardinality": Object { + "field": "tls.server.hash.sha256", }, }, - "collapse": Object { - "field": "tls.server.hash.sha256", - "inner_hits": Object { - "_source": Object { - "includes": Array [ - "monitor.id", - "monitor.name", - "url.full", - "config_id", - ], - }, - "collapse": Object { - "field": "monitor.id", - }, - "name": "monitors", - "sort": Array [ - Object { - "monitor.id": "asc", - }, + }, + "collapse": Object { + "field": "tls.server.hash.sha256", + "inner_hits": Object { + "_source": Object { + "includes": Array [ + "monitor.id", + "monitor.name", + "url.full", + "config_id", ], }, + "collapse": Object { + "field": "monitor.id", + }, + "name": "monitors", + "sort": Array [ + Object { + "monitor.id": "asc", + }, + ], }, - "from": 30, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "from": 30, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "exists": Object { - "field": "tls.server.hash.sha256", - }, + }, + Object { + "exists": Object { + "field": "tls.server.hash.sha256", }, - Object { - "range": Object { - "monitor.timespan": Object { - "gte": 10000, - "lte": 10000, - }, + }, + Object { + "range": Object { + "monitor.timespan": Object { + "gte": 10000, + "lte": 10000, }, }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "range": Object { - "tls.certificate_not_valid_after": Object { - "lte": 10000, - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "range": Object { + "tls.certificate_not_valid_after": Object { + "lte": 10000, }, }, - ], - }, + }, + ], }, - ], - "minimum_should_match": 1, - "should": Array [ - Object { - "multi_match": Object { - "fields": Array [ - "monitor.id.text", - "monitor.name.text", - "url.full.text", - "tls.server.x509.subject.common_name.text", - "tls.server.x509.issuer.common_name.text", - ], - "query": "my_common_name", - "type": "phrase_prefix", - }, + }, + ], + "minimum_should_match": 1, + "should": Array [ + Object { + "multi_match": Object { + "fields": Array [ + "monitor.id.text", + "monitor.name.text", + "url.full.text", + "tls.server.x509.subject.common_name.text", + "tls.server.x509.issuer.common_name.text", + ], + "query": "my_common_name", + "type": "phrase_prefix", }, - ], - }, - }, - "size": 30, - "sort": Array [ - Object { - "tls.server.x509.not_after": Object { - "order": "desc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 30, + "sort": Array [ + Object { + "tls.server.x509.not_after": Object { + "order": "desc", + }, + }, + ], }, Object { "meta": true, diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.ts index d3d0f512621c9..6319cd0bb9e87 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_certs.ts @@ -31,11 +31,7 @@ const getCertsResults = async ( const searchBody = getCertsRequestBody(requestParams); - const request = { body: searchBody }; - - const { body: result } = await uptimeEsClient.search({ - body: searchBody, - }); + const { body: result } = await uptimeEsClient.search(searchBody); return result; }; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_details.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_details.ts index f32cc5f3353a6..a1e4a47c02627 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_details.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_details.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { JourneyStep, @@ -41,7 +41,7 @@ export const getJourneyDetails: UMElasticsearchQueryFn< }; const { body: thisJourney } = await uptimeEsClient.search( - { body: baseParams }, + baseParams, 'getJourneyDetailsCurrentJourney' ); @@ -109,11 +109,11 @@ export const getJourneyDetails: UMElasticsearchQueryFn< }; const { body: previousJourneyResult } = await uptimeEsClient.search( - { body: previousParams }, + previousParams, 'getJourneyDetailsNextJourney' ); const { body: nextJourneyResult } = await uptimeEsClient.search( - { body: nextParams }, + nextParams, 'getJourneyDetailsPreviousJourney' ); const previousJourney: any = diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_failed_steps.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_failed_steps.ts index c48aecd8cf1dd..5a222c0b2723e 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_failed_steps.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_failed_steps.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { JourneyStep } from '../../../../common/runtime_types/ping/synthetics'; @@ -50,7 +50,7 @@ export const getJourneyFailedSteps: UMElasticsearchQueryFn< size: 500, }; - const { body: result } = await uptimeEsClient.search({ body: params }); + const { body: result } = await uptimeEsClient.search(params); return result.hits.hits.map(({ _id, _source }) => { const step = Object.assign({ _id }, _source) as JourneyStep; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot.ts index a7cbc0cb50d33..dc184d747ae4a 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { UMElasticsearchQueryFn } from '../adapters'; import { RefResult, FullScreenshot } from '../../../../common/runtime_types/ping/synthetics'; @@ -58,7 +58,7 @@ export const getJourneyScreenshot: UMElasticsearchQueryFn< }, }; - const result = await uptimeEsClient.search({ body }); + const result = await uptimeEsClient.search(body); const screenshotsOrRefs = (result.body.aggregations?.step.image.hits.hits as ResultType[]) ?? null; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot_blocks.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot_blocks.ts index 954fa1d76e113..3d524e5cc11a8 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot_blocks.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_screenshot_blocks.ts @@ -37,7 +37,7 @@ export const getJourneyScreenshotBlocks: UMElasticsearchQueryFn< size: 1000, }; - const fetchScreenshotBlocksResult = await uptimeEsClient.search({ body }); + const fetchScreenshotBlocksResult = await uptimeEsClient.search(body); return (fetchScreenshotBlocksResult.body.hits.hits as ScreenshotBlockResultType[]).map( ({ _id, _source }) => ({ diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.test.ts index 46986cc47f3e5..cc1eadc88c8ce 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.test.ts @@ -118,7 +118,7 @@ describe('getJourneySteps request module', () => { const call: any = mockEsClient.search.mock.calls[0][0]; // check that default `synthetics.type` value is supplied, - expect(call.body.query.bool.filter[0]).toMatchInlineSnapshot(` + expect(call.query.bool.filter[0]).toMatchInlineSnapshot(` Object { "terms": Object { "synthetics.type": Array [ @@ -133,7 +133,7 @@ describe('getJourneySteps request module', () => { `); // given check group is used for the terms filter - expect(call.body.query.bool.filter[1]).toMatchInlineSnapshot(` + expect(call.query.bool.filter[1]).toMatchInlineSnapshot(` Object { "term": Object { "monitor.check_group": "2bf952dc-64b5-11eb-8b3b-42010a84000d", @@ -142,7 +142,7 @@ describe('getJourneySteps request module', () => { `); // should sort by step index, then timestamp - expect(call.body.sort).toMatchInlineSnapshot(` + expect(call.sort).toMatchInlineSnapshot(` Array [ Object { "synthetics.step.index": Object { @@ -184,7 +184,7 @@ describe('getJourneySteps request module', () => { const call: any = mockEsClient.search.mock.calls[0][0]; // assert that filters for only the provided step types are used - expect(call.body.query.bool.filter[0]).toMatchInlineSnapshot(` + expect(call.query.bool.filter[0]).toMatchInlineSnapshot(` Object { "terms": Object { "synthetics.type": Array [ diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.ts index c200a4c22a671..d28b839168ee2 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_journey_steps.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { JourneyStep } from '../../../../common/runtime_types/ping/synthetics'; @@ -63,7 +63,7 @@ export const getJourneySteps: UMElasticsearchQueryFn< }, size: 500, }; - const { body: result } = await uptimeEsClient.search({ body: params }, 'getJourneySteps'); + const { body: result } = await uptimeEsClient.search(params, 'getJourneySteps'); const steps = result.hits.hits.map( ({ _id, _source }) => Object.assign({ _id }, _source) as ResultType diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_last_successful_check.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_last_successful_check.ts index 2b11d46bca3fb..1746d99cb50ee 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_last_successful_check.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_last_successful_check.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { Ping } from '../../../../common/runtime_types/ping'; @@ -19,7 +19,7 @@ export const getLastSuccessfulStepParams = ({ monitorId, timestamp, location, -}: GetStepScreenshotParams): estypes.SearchRequest['body'] => { +}: GetStepScreenshotParams): estypes.SearchRequest => { return { size: 1, sort: [ @@ -90,7 +90,7 @@ export const getLastSuccessfulCheck: UMElasticsearchQueryFn< location, }); - const { body: result } = await uptimeEsClient.search({ body: lastSuccessCheckParams }); + const { body: result } = await uptimeEsClient.search(lastSuccessCheckParams); if (result.hits.total.value < 1) { return null; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.test.ts index 8070e5142516d..31e973da27bd5 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.test.ts @@ -15,44 +15,42 @@ describe('getLatestMonitor', () => { beforeEach(() => { expectedGetLatestSearchParams = { index: DYNAMIC_SETTINGS_DEFAULTS.heartbeatIndices, - body: { - query: { - bool: { - filter: [ - { - exists: { - field: 'summary', - }, + query: { + bool: { + filter: [ + { + exists: { + field: 'summary', }, - { - bool: { - must_not: { - exists: { - field: 'run_once', - }, + }, + { + bool: { + must_not: { + exists: { + field: 'run_once', }, }, }, - { - range: { - '@timestamp': { - gte: 'now-1h', - lte: 'now', - }, + }, + { + range: { + '@timestamp': { + gte: 'now-1h', + lte: 'now', }, }, - { - term: { 'monitor.id': 'testMonitor' }, - }, - ], - }, - }, - size: 1, - _source: ['url', 'monitor', 'observer', '@timestamp', 'tls.*', 'http', 'error', 'tags'], - sort: { - '@timestamp': { order: 'desc' }, + }, + { + term: { 'monitor.id': 'testMonitor' }, + }, + ], }, }, + size: 1, + _source: ['url', 'monitor', 'observer', '@timestamp', 'tls.*', 'http', 'error', 'tags'], + sort: { + '@timestamp': { order: 'desc' }, + }, }; mockEsSearchResult = { hits: { diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.ts index a4e69121887d1..9afb5e43e049b 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_latest_monitor.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { EXCLUDE_RUN_ONCE_FILTER, SUMMARY_FILTER, @@ -60,7 +60,7 @@ export const getLatestMonitor: UMElasticsearchQueryFn { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "down_sum": Object { - "sum": Object { - "field": "summary.down", - "missing": 0, - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "down_sum": Object { + "sum": Object { + "field": "summary.down", + "missing": 0, }, - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, + }, + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", }, - ], - }, - }, - "filtered": Object { - "bucket_selector": Object { - "buckets_path": Object { - "threshold": "ratio.value", }, - "script": "params.threshold < 0.54", + ], + }, + }, + "filtered": Object { + "bucket_selector": Object { + "buckets_path": Object { + "threshold": "ratio.value", }, + "script": "params.threshold < 0.54", }, - "ratio": Object { - "bucket_script": Object { - "buckets_path": Object { - "downTotal": "down_sum", - "upTotal": "up_sum", - }, - "script": " + }, + "ratio": Object { + "bucket_script": Object { + "buckets_path": Object { + "downTotal": "down_sum", + "upTotal": "up_sum", + }, + "script": " if (params.upTotal + params.downTotal > 0) { return params.upTotal / (params.upTotal + params.downTotal); } return null;", - }, }, - "up_sum": Object { - "sum": Object { - "field": "summary.up", - "missing": 0, - }, + }, + "up_sum": Object { + "sum": Object { + "field": "summary.up", + "missing": 0, }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-2w", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-2w", + "lte": "now", }, }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "monitor.id": "apm-dev", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "monitor.id": "apm-dev", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "monitor.id": "auto-http-0X8D6082B94BBE3B8A", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "monitor.id": "auto-http-0X8D6082B94BBE3B8A", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); }); @@ -314,108 +312,106 @@ describe('monitor availability', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "down_sum": Object { - "sum": Object { - "field": "summary.down", - "missing": 0, - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "down_sum": Object { + "sum": Object { + "field": "summary.down", + "missing": 0, }, - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, + }, + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", }, - ], - }, - }, - "filtered": Object { - "bucket_selector": Object { - "buckets_path": Object { - "threshold": "ratio.value", }, - "script": "params.threshold < 0.69", + ], + }, + }, + "filtered": Object { + "bucket_selector": Object { + "buckets_path": Object { + "threshold": "ratio.value", }, + "script": "params.threshold < 0.69", }, - "ratio": Object { - "bucket_script": Object { - "buckets_path": Object { - "downTotal": "down_sum", - "upTotal": "up_sum", - }, - "script": " + }, + "ratio": Object { + "bucket_script": Object { + "buckets_path": Object { + "downTotal": "down_sum", + "upTotal": "up_sum", + }, + "script": " if (params.upTotal + params.downTotal > 0) { return params.upTotal / (params.upTotal + params.downTotal); } return null;", - }, - }, - "up_sum": Object { - "sum": Object { - "field": "summary.up", - "missing": 0, - }, }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, - }, - }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, - }, - }, - ], + "up_sum": Object { + "sum": Object { + "field": "summary.up", + "missing": 0, + }, }, }, - }, - "query": Object { - "bool": Object { - "filter": Array [ + "composite": Object { + "size": 2000, + "sources": Array [ Object { - "exists": Object { - "field": "summary", - }, - }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, }, Object { - "range": Object { - "@timestamp": Object { - "gte": "now-23d", - "lte": "now", + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, }, ], }, }, - "size": 0, }, "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", + }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", + }, + }, + }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-23d", + "lte": "now", + }, + }, + }, + ], + }, + }, + "size": 0, } `); @@ -649,7 +645,112 @@ describe('monitor availability', () => { expect(esMock.search).toHaveBeenCalledTimes(2); expect(params).toMatchInlineSnapshot(` Object { - "body": Object { + "aggs": Object { + "monitors": Object { + "aggs": Object { + "down_sum": Object { + "sum": Object { + "field": "summary.down", + "missing": 0, + }, + }, + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, + ], + }, + }, + "filtered": Object { + "bucket_selector": Object { + "buckets_path": Object { + "threshold": "ratio.value", + }, + "script": "params.threshold < 0.98", + }, + }, + "ratio": Object { + "bucket_script": Object { + "buckets_path": Object { + "downTotal": "down_sum", + "upTotal": "up_sum", + }, + "script": " + if (params.upTotal + params.downTotal > 0) { + return params.upTotal / (params.upTotal + params.downTotal); + } return null;", + }, + }, + "up_sum": Object { + "sum": Object { + "field": "summary.up", + "missing": 0, + }, + }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", + }, + }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, + }, + }, + }, + ], + }, + }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", + }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", + }, + }, + }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-3M", + "lte": "now", + }, + }, + }, + ], + }, + }, + "size": 0, + } + `); + + expect(esMock.search.mock.calls[1]).toMatchInlineSnapshot(` + Array [ + Object { "aggs": Object { "monitors": Object { "aggs": Object { @@ -699,6 +800,10 @@ describe('monitor availability', () => { }, }, "composite": Object { + "after": Object { + "location": "harrisburg", + "monitorId": "baz", + }, "size": 2000, "sources": Array [ Object { @@ -720,6 +825,7 @@ describe('monitor availability', () => { }, }, }, + "index": "heartbeat-*", "query": Object { "bool": Object { "filter": Array [ @@ -750,120 +856,6 @@ describe('monitor availability', () => { }, "size": 0, }, - "index": "heartbeat-*", - } - `); - - expect(esMock.search.mock.calls[1]).toMatchInlineSnapshot(` - Array [ - Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "down_sum": Object { - "sum": Object { - "field": "summary.down", - "missing": 0, - }, - }, - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, - }, - ], - }, - }, - "filtered": Object { - "bucket_selector": Object { - "buckets_path": Object { - "threshold": "ratio.value", - }, - "script": "params.threshold < 0.98", - }, - }, - "ratio": Object { - "bucket_script": Object { - "buckets_path": Object { - "downTotal": "down_sum", - "upTotal": "up_sum", - }, - "script": " - if (params.upTotal + params.downTotal > 0) { - return params.upTotal / (params.upTotal + params.downTotal); - } return null;", - }, - }, - "up_sum": Object { - "sum": Object { - "field": "summary.up", - "missing": 0, - }, - }, - }, - "composite": Object { - "after": Object { - "location": "harrisburg", - "monitorId": "baz", - }, - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, - }, - }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, - }, - }, - ], - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, - }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, - }, - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-3M", - "lte": "now", - }, - }, - }, - ], - }, - }, - "size": 0, - }, - "index": "heartbeat-*", - }, Object { "meta": true, }, @@ -897,119 +889,117 @@ describe('monitor availability', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "down_sum": Object { - "sum": Object { - "field": "summary.down", - "missing": 0, - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "down_sum": Object { + "sum": Object { + "field": "summary.down", + "missing": 0, }, - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, + }, + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", }, - ], - }, - }, - "filtered": Object { - "bucket_selector": Object { - "buckets_path": Object { - "threshold": "ratio.value", }, - "script": "params.threshold < 0.99", + ], + }, + }, + "filtered": Object { + "bucket_selector": Object { + "buckets_path": Object { + "threshold": "ratio.value", }, + "script": "params.threshold < 0.99", }, - "ratio": Object { - "bucket_script": Object { - "buckets_path": Object { - "downTotal": "down_sum", - "upTotal": "up_sum", - }, - "script": " + }, + "ratio": Object { + "bucket_script": Object { + "buckets_path": Object { + "downTotal": "down_sum", + "upTotal": "up_sum", + }, + "script": " if (params.upTotal + params.downTotal > 0) { return params.upTotal / (params.upTotal + params.downTotal); } return null;", - }, }, - "up_sum": Object { - "sum": Object { - "field": "summary.up", - "missing": 0, - }, + }, + "up_sum": Object { + "sum": Object { + "field": "summary.up", + "missing": 0, }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-3s", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-3s", + "lte": "now", }, }, - Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "monitor.id": "foo", - }, + }, + Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "monitor.id": "foo", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); }); diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_availability.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_availability.ts index 2fde5666a44df..96b04e4b825d5 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_availability.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_availability.ts @@ -155,7 +155,7 @@ export const getMonitorAvailability: UMElasticsearchQueryFn< }, }; - const { body: result } = await uptimeEsClient.search({ body: esParams }); + const { body: result } = await uptimeEsClient.search(esParams); afterKey = result?.aggregations?.monitors?.after_key as AfterKey; queryResults.push(formatBuckets(result?.aggregations?.monitors?.buckets || [])); } while (afterKey !== undefined); diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.test.ts index 0ea91c500bffb..647d39a6fd28e 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.test.ts @@ -59,7 +59,7 @@ describe('getMonitorDetails', () => { const esParams = (uptimeEsClient.baseESClient.search as jest.Mock).mock.calls[0]; - expect(esParams[0].body.query).toEqual({ + expect(esParams[0].query).toEqual({ bool: { filter: [ { diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.ts index 1e842b7a4108a..491f9d1ce3752 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_details.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { CLIENT_ALERT_TYPES } from '../../../../common/constants/uptime_alerts'; import { UMElasticsearchQueryFn } from '../adapters'; import { MonitorDetails, Ping } from '../../../../common/runtime_types'; @@ -54,32 +54,30 @@ export const getMonitorAlerts = async ({ ); const esParams = createEsQuery({ - body: { - query: { - bool: { - filter: [ - { - term: { - 'monitor.id': monitorId, - }, + query: { + bool: { + filter: [ + { + term: { + 'monitor.id': monitorId, }, - ] as QueryDslQueryContainer[], - }, - }, - size: 0, - aggs: { - monitors: { - terms: { - field: 'monitor.id', - size: 1000, }, + ] as QueryDslQueryContainer[], + }, + }, + size: 0, + aggs: { + monitors: { + terms: { + field: 'monitor.id', + size: 1000, }, }, }, }); if (parsedFilters) { - esParams.body.query.bool.filter.push(parsedFilters); + esParams.query.bool.filter.push(parsedFilters); } const { body: result } = await uptimeEsClient.search( @@ -138,7 +136,7 @@ export const getMonitorDetails: UMElasticsearchQueryFn< ], }; - const { body: result } = await uptimeEsClient.search({ body: params }, 'getMonitorDetails'); + const { body: result } = await uptimeEsClient.search(params, 'getMonitorDetails'); const data = result.hits.hits[0]?._source as Ping & { '@timestamp': string }; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.test.ts index 16dd761180ae0..bee5c618515cd 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.test.ts @@ -26,7 +26,7 @@ describe('ElasticsearchMonitorsAdapter', () => { set( mockEsClient.search.mock.calls[0], - 'body.aggs.timeseries.date_histogram.fixed_interval', + 'aggs.timeseries.date_histogram.fixed_interval', '36000ms' ); expect(mockEsClient.search.mock.calls[0]).toMatchSnapshot(); diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.ts index cb0ab17f656fc..28d4e576c579a 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_duration.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { EXCLUDE_RUN_ONCE_FILTER, SUMMARY_FILTER, @@ -64,7 +64,7 @@ export const getMonitorDurationChart: UMElasticsearchQueryFn< }, }; - const { body: result } = await uptimeEsClient.search({ body: params }); + const { body: result } = await uptimeEsClient.search(params); const dateHistogramBuckets: any[] = result?.aggregations?.timeseries?.buckets ?? []; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_locations.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_locations.ts index 659eec8bb375a..7ec0b0729416d 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_locations.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_locations.ts @@ -91,7 +91,7 @@ export const getMonitorLocations: UMElasticsearchQueryFn< }, }; - const { body: result } = await uptimeEsClient.search({ body: params }); + const { body: result } = await uptimeEsClient.search(params); const locations = result?.aggregations?.location?.buckets ?? []; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.test.ts index dc7760d8f31f7..d3d6b97ea50b6 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.test.ts @@ -98,127 +98,125 @@ describe('getMonitorStatus', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "status": Object { - "terms": Object { - "field": "monitor.status", - }, + }, + Object { + "status": Object { + "terms": Object { + "field": "monitor.status", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "summary.down": Object { - "gt": "0", - }, + }, + Object { + "range": Object { + "summary.down": Object { + "gt": "0", }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-24h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-24h", + "lte": "now", }, }, - Object { - "range": Object { - "monitor.timespan": Object { - "gte": "now-10m", - "lte": "now-1m", - }, + }, + Object { + "range": Object { + "monitor.timespan": Object { + "gte": "now-10m", + "lte": "now-1m", }, }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "monitor.id": "apm-dev", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "monitor.id": "apm-dev", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "monitor.id": "auto-http-0X8D6082B94BBE3B8A", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "monitor.id": "auto-http-0X8D6082B94BBE3B8A", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); }); @@ -248,112 +246,110 @@ describe('getMonitorStatus', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "status": Object { - "terms": Object { - "field": "monitor.status", - }, + }, + Object { + "status": Object { + "terms": Object { + "field": "monitor.status", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "summary.down": Object { - "gt": "0", - }, + }, + Object { + "range": Object { + "summary.down": Object { + "gt": "0", }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-24h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-24h", + "lte": "now", }, }, - Object { - "range": Object { - "monitor.timespan": Object { - "gte": "now-2m", - "lte": "now", - }, + }, + Object { + "range": Object { + "monitor.timespan": Object { + "gte": "now-2m", + "lte": "now", }, }, - Object { - "bool": Object { - "should": Array [ - Object { - "term": Object { - "observer.geo.name": "fairbanks", - }, + }, + Object { + "bool": Object { + "should": Array [ + Object { + "term": Object { + "observer.geo.name": "fairbanks", }, - Object { - "term": Object { - "observer.geo.name": "harrisburg", - }, + }, + Object { + "term": Object { + "observer.geo.name": "harrisburg", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); }); @@ -435,145 +431,143 @@ describe('getMonitorStatus', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "status": Object { - "terms": Object { - "field": "monitor.status", - }, + }, + Object { + "status": Object { + "terms": Object { + "field": "monitor.status", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "summary.down": Object { - "gt": "0", - }, + }, + Object { + "range": Object { + "summary.down": Object { + "gt": "0", }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-24h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-24h", + "lte": "now", }, }, - Object { - "range": Object { - "monitor.timespan": Object { - "gte": "now-15m", - "lte": "now", - }, + }, + Object { + "range": Object { + "monitor.timespan": Object { + "gte": "now-15m", + "lte": "now", }, }, - Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "tags": "org:google", - }, + }, + Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "tags": "org:google", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "monitor.type": "http", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "monitor.type": "http", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "monitor.type": "tcp", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "monitor.type": "tcp", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); }); @@ -615,105 +609,103 @@ describe('getMonitorStatus', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "status": Object { - "terms": Object { - "field": "monitor.status", - }, + }, + Object { + "status": Object { + "terms": Object { + "field": "monitor.status", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "summary.down": Object { - "gt": "0", - }, + }, + Object { + "range": Object { + "summary.down": Object { + "gt": "0", }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-24h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-24h", + "lte": "now", }, }, - Object { - "range": Object { - "monitor.timespan": Object { - "gte": "now-15m", - "lte": "now", - }, + }, + Object { + "range": Object { + "monitor.timespan": Object { + "gte": "now-15m", + "lte": "now", }, }, - Object { - "bool": Object { - "filter": Object { - "exists": Object { - "field": "monitor.status", - }, + }, + Object { + "bool": Object { + "filter": Object { + "exists": Object { + "field": "monitor.status", }, }, }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); }); @@ -770,96 +762,94 @@ describe('getMonitorStatus', () => { const [params] = esMock.search.mock.calls[0]; expect(params).toMatchInlineSnapshot(` Object { - "body": Object { - "aggs": Object { - "monitors": Object { - "aggs": Object { - "fields": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - }, + "aggs": Object { + "monitors": Object { + "aggs": Object { + "fields": Object { + "top_hits": Object { + "size": 1, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], }, }, - "composite": Object { - "size": 2000, - "sources": Array [ - Object { - "monitorId": Object { - "terms": Object { - "field": "monitor.id", - }, + }, + "composite": Object { + "size": 2000, + "sources": Array [ + Object { + "monitorId": Object { + "terms": Object { + "field": "monitor.id", }, }, - Object { - "status": Object { - "terms": Object { - "field": "monitor.status", - }, + }, + Object { + "status": Object { + "terms": Object { + "field": "monitor.status", }, }, - Object { - "location": Object { - "terms": Object { - "field": "observer.geo.name", - "missing_bucket": true, - }, + }, + Object { + "location": Object { + "terms": Object { + "field": "observer.geo.name", + "missing_bucket": true, }, }, - ], - }, + }, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "summary.down": Object { - "gt": "0", - }, + }, + Object { + "range": Object { + "summary.down": Object { + "gt": "0", }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-24h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-24h", + "lte": "now", }, }, - Object { - "range": Object { - "monitor.timespan": Object { - "gte": "now-12m", - "lte": "now-2m", - }, + }, + Object { + "range": Object { + "monitor.timespan": Object { + "gte": "now-12m", + "lte": "now-2m", }, }, - ], - }, + }, + ], }, - "size": 0, }, - "index": "heartbeat-*", + "size": 0, } `); expect(result.length).toBe(3); diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.ts index 1c99d1a6dd022..3bea5efb78eca 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_monitor_status.ts @@ -6,7 +6,7 @@ */ import { JsonObject } from '@kbn/utility-types'; -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { PromiseType } from 'utility-types'; import { formatDurationFromTimeUnitChar, TimeUnitChar } from '@kbn/observability-plugin/common'; import { @@ -91,81 +91,79 @@ const executeQueryParams = async ({ locations: string[]; }) => { const queryParams = createEsQuery({ - body: { - query: { - bool: { - filter: [ - SUMMARY_FILTER, - EXCLUDE_RUN_ONCE_FILTER, - { - range: { - 'summary.down': { - gt: '0', - }, + query: { + bool: { + filter: [ + SUMMARY_FILTER, + EXCLUDE_RUN_ONCE_FILTER, + { + range: { + 'summary.down': { + gt: '0', }, }, - { - range: { - '@timestamp': { - gte: timestampRange.from, - lte: timestampRange.to, - }, + }, + { + range: { + '@timestamp': { + gte: timestampRange.from, + lte: timestampRange.to, }, }, - { - range: { - 'monitor.timespan': { - gte: timespanRange.from, - lte: timespanRange.to, - }, + }, + { + range: { + 'monitor.timespan': { + gte: timespanRange.from, + lte: timespanRange.to, }, }, - // append user filters, if defined - ...(filters?.bool ? [filters] : []), - ] as QueryDslQueryContainer[], - }, + }, + // append user filters, if defined + ...(filters?.bool ? [filters] : []), + ] as QueryDslQueryContainer[], }, - size: 0, - aggs: { - monitors: { - composite: { - size: 2000, - /** - * We "paginate" results by utilizing the `afterKey` field - * to tell Elasticsearch where it should start on subsequent queries. - */ - ...(afterKey ? { after: afterKey } : {}), - sources: asMutableArray([ - { - monitorId: { - terms: { - field: 'monitor.id', - }, + }, + size: 0, + aggs: { + monitors: { + composite: { + size: 2000, + /** + * We "paginate" results by utilizing the `afterKey` field + * to tell Elasticsearch where it should start on subsequent queries. + */ + ...(afterKey ? { after: afterKey } : {}), + sources: asMutableArray([ + { + monitorId: { + terms: { + field: 'monitor.id', }, }, - { - status: { - terms: { - field: 'monitor.status', - }, + }, + { + status: { + terms: { + field: 'monitor.status', }, }, - { - location: { - terms: { - field: 'observer.geo.name', - missing_bucket: true, - }, + }, + { + location: { + terms: { + field: 'observer.geo.name', + missing_bucket: true, }, }, - ] as const), - }, - aggs: { - fields: { - top_hits: { - size: 1, - sort: [{ '@timestamp': 'desc' }], - }, + }, + ] as const), + }, + aggs: { + fields: { + top_hits: { + size: 1, + sort: [{ '@timestamp': 'desc' }], }, }, }, @@ -177,7 +175,7 @@ const executeQueryParams = async ({ * Perform a logical `and` against the selected location filters. */ if (locations.length) { - queryParams.body.query.bool.filter.push(getLocationClause(locations)); + queryParams.query.bool.filter.push(getLocationClause(locations)); } const { body: result } = await uptimeEsClient.search(queryParams); diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.test.ts index 29d9386c37cf3..3851f07f6af23 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.test.ts @@ -188,32 +188,30 @@ describe('getNetworkEvents', () => { Array [ Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "synthetics.type": "journey/network_info", - }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "term": Object { + "synthetics.type": "journey/network_info", }, - Object { - "term": Object { - "monitor.check_group": "my-fake-group", - }, + }, + Object { + "term": Object { + "monitor.check_group": "my-fake-group", }, - Object { - "term": Object { - "synthetics.step.index": 1, - }, + }, + Object { + "term": Object { + "synthetics.step.index": 1, }, - ], - }, + }, + ], }, - "size": 1000, - "track_total_hits": true, }, - "index": "heartbeat-*", + "size": 1000, + "track_total_hits": true, }, Object { "meta": true, diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.ts index 74c8e85ff3cb2..bcf811712d816 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_network_events.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { NetworkEvent } from '../../../../common/runtime_types'; @@ -44,7 +44,7 @@ export const getNetworkEvents: UMElasticsearchQueryFn< size: 1000, }; - const { body: result } = await uptimeEsClient.search({ body: params }); + const { body: result } = await uptimeEsClient.search(params); let isWaterfallSupported = false; let hasNavigationRequest = false; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_ping_histogram.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_ping_histogram.ts index 192c77bbb0c32..d25c7af16dbee 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_ping_histogram.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_ping_histogram.ts @@ -47,31 +47,29 @@ export const getPingHistogram: UMElasticsearchQueryFn< } const params = createEsQuery({ - body: { - query: { - bool: { - filter: [...filter, SUMMARY_FILTER, EXCLUDE_RUN_ONCE_FILTER], - }, + query: { + bool: { + filter: [...filter, SUMMARY_FILTER, EXCLUDE_RUN_ONCE_FILTER], }, - size: 0, - aggs: { - timeseries: { - date_histogram: { - field: '@timestamp', - fixed_interval: bucketSize || minInterval + 'ms', - missing: '0', - time_zone: timeZone, - }, - aggs: { - down: { - sum: { - field: 'summary.down', - }, + }, + size: 0, + aggs: { + timeseries: { + date_histogram: { + field: '@timestamp', + fixed_interval: bucketSize || minInterval + 'ms', + missing: '0', + time_zone: timeZone, + }, + aggs: { + down: { + sum: { + field: 'summary.down', }, - up: { - sum: { - field: 'summary.up', - }, + }, + up: { + sum: { + field: 'summary.up', }, }, }, diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.test.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.test.ts index a58c7f5516ff8..0cb5be981dc01 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.test.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.test.ts @@ -125,45 +125,43 @@ describe('getAll', () => { expect(mockEsClient.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-1h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-1h", + "lte": "now", }, }, - ], - }, - }, - "size": 12, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "asc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 12, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "asc", + }, + }, + ], }, Object { "meta": true, @@ -187,45 +185,43 @@ describe('getAll', () => { expect(mockEsClient.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-1h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-1h", + "lte": "now", }, }, - ], - }, - }, - "size": 12, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 12, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, + ], }, Object { "meta": true, @@ -249,45 +245,43 @@ describe('getAll', () => { expect(mockEsClient.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-1h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-1h", + "lte": "now", }, }, - ], - }, - }, - "size": 25, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 25, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, + ], }, Object { "meta": true, @@ -311,50 +305,48 @@ describe('getAll', () => { expect(mockEsClient.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-1h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-1h", + "lte": "now", }, }, - Object { - "term": Object { - "monitor.id": "testmonitorid", - }, + }, + Object { + "term": Object { + "monitor.id": "testmonitorid", }, - ], - }, - }, - "size": 25, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 25, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, + ], }, Object { "meta": true, @@ -377,7 +369,7 @@ describe('getAll', () => { expect(mockEsClient.search).toHaveBeenCalledTimes(1); // @ts-expect-error the response is not typed, but should always result in this object, and in this order, // unless the code that builds the query is modified. - expect(mockEsClient.search.mock.calls[0][0].body.query.bool.filter[1]).toMatchInlineSnapshot(` + expect(mockEsClient.search.mock.calls[0][0].query.bool.filter[1]).toMatchInlineSnapshot(` Object { "bool": Object { "must_not": Object { @@ -419,50 +411,48 @@ describe('getAll', () => { expect(mockEsClient.search.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { - "body": Object { - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "exists": Object { - "field": "summary", - }, + "index": "heartbeat-*", + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "exists": Object { + "field": "summary", }, - Object { - "bool": Object { - "must_not": Object { - "exists": Object { - "field": "run_once", - }, + }, + Object { + "bool": Object { + "must_not": Object { + "exists": Object { + "field": "run_once", }, }, }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-1h", - "lte": "now", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "gte": "now-1h", + "lte": "now", }, }, - Object { - "term": Object { - "monitor.status": "down", - }, + }, + Object { + "term": Object { + "monitor.status": "down", }, - ], - }, - }, - "size": 25, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", }, - }, - ], + ], + }, }, - "index": "heartbeat-*", + "size": 25, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", + }, + }, + ], }, Object { "meta": true, diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.ts index 2e94992b0d7f0..f545467476de7 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/get_pings.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { EXCLUDE_RUN_ONCE_FILTER, SUMMARY_FILTER, @@ -80,7 +80,7 @@ export const getPings: UMElasticsearchQueryFn = a body: { hits: { hits, total }, }, - } = await uptimeEsClient.search({ body: searchBody }); + } = await uptimeEsClient.search(searchBody); const pings: Ping[] = hits.map((doc: any) => { const { _id, _source } = doc; diff --git a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/test_helpers.ts b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/test_helpers.ts index e2a9fc4d7c608..02df500f11124 100644 --- a/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/test_helpers.ts +++ b/x-pack/solutions/observability/plugins/uptime/server/legacy_uptime/lib/requests/test_helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AggregationsAggregate } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { AggregationsAggregate } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { elasticsearchServiceMock, savedObjectsClientMock } from '@kbn/core/server/mocks'; diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/client_metrics_query.test.ts.snap b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/client_metrics_query.test.ts.snap index 9957c50bf52c9..62040e5c9c63e 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/client_metrics_query.test.ts.snap +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/client_metrics_query.test.ts.snap @@ -2,75 +2,73 @@ exports[`clientMetricsQuery fetches client metrics 1`] = ` Object { - "body": Object { - "aggs": Object { - "hasFetchStartField": Object { - "aggs": Object { - "backEnd": Object { - "percentiles": Object { - "field": "transaction.marks.agent.timeToFirstByte", - "hdr": Object { - "number_of_significant_value_digits": 3, - }, - "percents": Array [ - 50, - ], + "aggs": Object { + "hasFetchStartField": Object { + "aggs": Object { + "backEnd": Object { + "percentiles": Object { + "field": "transaction.marks.agent.timeToFirstByte", + "hdr": Object { + "number_of_significant_value_digits": 3, }, + "percents": Array [ + 50, + ], }, - "totalPageLoadDuration": Object { - "percentiles": Object { - "field": "transaction.duration.us", - "hdr": Object { - "number_of_significant_value_digits": 3, - }, - "percents": Array [ - 50, - ], + }, + "totalPageLoadDuration": Object { + "percentiles": Object { + "field": "transaction.duration.us", + "hdr": Object { + "number_of_significant_value_digits": 3, }, + "percents": Array [ + 50, + ], }, }, - "filter": Object { - "exists": Object { - "field": "transaction.marks.navigationTiming.fetchStart", - }, + }, + "filter": Object { + "exists": Object { + "field": "transaction.marks.navigationTiming.fetchStart", }, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "term": Object { - "transaction.type": "page-load", - }, + }, + Object { + "term": Object { + "transaction.type": "page-load", }, - Object { - "terms": Object { - "processor.event": Array [ - "transaction", - ], - }, + }, + Object { + "terms": Object { + "processor.event": Array [ + "transaction", + ], }, - Object { - "term": Object { - "service.environment": "staging", - }, + }, + Object { + "term": Object { + "service.environment": "staging", }, - ], - "must_not": Array [], - }, + }, + ], + "must_not": Array [], }, - "size": 0, - "track_total_hits": true, }, + "size": 0, + "track_total_hits": true, } -`; \ No newline at end of file +`; diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/core_web_vitals_query.test.ts.snap b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/core_web_vitals_query.test.ts.snap index 6e9764ce13df3..963601e972374 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/core_web_vitals_query.test.ts.snap +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/core_web_vitals_query.test.ts.snap @@ -2,102 +2,100 @@ exports[`core web vitals query fetches rum core vitals 1`] = ` Object { - "body": Object { - "aggs": Object { - "cls": Object { - "percentiles": Object { - "field": "transaction.experience.cls", - "percents": Array [ - 50, - ], - }, + "aggs": Object { + "cls": Object { + "percentiles": Object { + "field": "transaction.experience.cls", + "percents": Array [ + 50, + ], }, - "clsRanks": Object { - "percentile_ranks": Object { - "field": "transaction.experience.cls", - "keyed": false, - "values": Array [ - 0.1, - 0.25, - ], - }, + }, + "clsRanks": Object { + "percentile_ranks": Object { + "field": "transaction.experience.cls", + "keyed": false, + "values": Array [ + 0.1, + 0.25, + ], }, - "coreVitalPages": Object { - "filter": Object { - "exists": Object { - "field": "transaction.experience", - }, + }, + "coreVitalPages": Object { + "filter": Object { + "exists": Object { + "field": "transaction.experience", }, }, - "fcp": Object { - "percentiles": Object { - "field": "transaction.marks.agent.firstContentfulPaint", - "percents": Array [ - 50, - ], - }, + }, + "fcp": Object { + "percentiles": Object { + "field": "transaction.marks.agent.firstContentfulPaint", + "percents": Array [ + 50, + ], }, - "lcp": Object { - "percentiles": Object { - "field": "transaction.marks.agent.largestContentfulPaint", - "percents": Array [ - 50, - ], - }, + }, + "lcp": Object { + "percentiles": Object { + "field": "transaction.marks.agent.largestContentfulPaint", + "percents": Array [ + 50, + ], }, - "lcpRanks": Object { - "percentile_ranks": Object { - "field": "transaction.marks.agent.largestContentfulPaint", - "keyed": false, - "values": Array [ - 2500, - 4000, - ], - }, + }, + "lcpRanks": Object { + "percentile_ranks": Object { + "field": "transaction.marks.agent.largestContentfulPaint", + "keyed": false, + "values": Array [ + 2500, + 4000, + ], }, - "tbt": Object { - "percentiles": Object { - "field": "transaction.experience.tbt", - "percents": Array [ - 50, - ], - }, + }, + "tbt": Object { + "percentiles": Object { + "field": "transaction.experience.tbt", + "percents": Array [ + 50, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 5000, - }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 5000, }, }, - Object { - "term": Object { - "transaction.type": "page-load", - }, + }, + Object { + "term": Object { + "transaction.type": "page-load", }, - Object { - "terms": Object { - "processor.event": Array [ - "transaction", - ], - }, + }, + Object { + "terms": Object { + "processor.event": Array [ + "transaction", + ], }, - Object { - "exists": Object { - "field": "transaction.marks.navigationTiming.fetchStart", - }, + }, + Object { + "exists": Object { + "field": "transaction.marks.navigationTiming.fetchStart", }, - ], - "must_not": Array [], - }, + }, + ], + "must_not": Array [], }, - "size": 0, }, + "size": 0, } `; diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/js_errors_query.test.ts.snap b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/js_errors_query.test.ts.snap index e334167dd087f..29c047005f931 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/js_errors_query.test.ts.snap +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/js_errors_query.test.ts.snap @@ -2,94 +2,91 @@ exports[`jsErrorsQuery fetches js errors 1`] = ` Object { - "body": Object { - "aggs": Object { - "errors": Object { - "aggs": Object { - "bucket_truncate": Object { - "bucket_sort": Object { - "from": 0, - "size": 5, - }, + "aggs": Object { + "errors": Object { + "aggs": Object { + "bucket_truncate": Object { + "bucket_sort": Object { + "from": 0, + "size": 5, }, - "impactedPages": Object { - "aggs": Object { - "pageCount": Object { - "cardinality": Object { - "field": "transaction.id", - }, - }, - }, - "filter": Object { - "term": Object { - "transaction.type": "page-load", + }, + "impactedPages": Object { + "aggs": Object { + "pageCount": Object { + "cardinality": Object { + "field": "transaction.id", }, }, }, - "sample": Object { - "top_hits": Object { - "_source": Array [ - "error.exception.message", - "error.exception.type", - "error.grouping_key", - "@timestamp", - ], - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], + "filter": Object { + "term": Object { + "transaction.type": "page-load", }, }, }, - "terms": Object { - "field": "error.grouping_key", - "size": 500, + "sample": Object { + "top_hits": Object { + "_source": Array [ + "error.exception.message", + "error.exception.type", + "error.grouping_key", + "@timestamp", + ], + "size": 1, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], + }, }, }, - "totalErrorGroups": Object { - "cardinality": Object { - "field": "error.grouping_key", - }, + "terms": Object { + "field": "error.grouping_key", + "size": 500, }, - "totalErrorPages": Object { - "cardinality": Object { - "field": "transaction.id", - }, + }, + "totalErrorGroups": Object { + "cardinality": Object { + "field": "error.grouping_key", }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + "totalErrorPages": Object { + "cardinality": Object { + "field": "transaction.id", + }, + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "term": Object { - "agent.name": "rum-js", - }, + }, + Object { + "term": Object { + "agent.name": "rum-js", }, - Object { - "terms": Object { - "processor.event": Array [ - "error", - ], - }, + }, + Object { + "terms": Object { + "processor.event": Array [ + "error", + ], }, - ], - "must_not": Array [], - }, + }, + ], + "must_not": Array [], }, - "size": 0, - "track_total_hits": true, }, + "size": 0, + "track_total_hits": true, } `; - diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/long_task_metrics_query.test.ts.snap b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/long_task_metrics_query.test.ts.snap index 55639e3a3f6b4..b4112b38e5d14 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/long_task_metrics_query.test.ts.snap +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/long_task_metrics_query.test.ts.snap @@ -2,76 +2,74 @@ exports[`longTaskMetricsQuery fetches long task metrics 1`] = ` Object { - "body": Object { - "aggs": Object { - "longTaskCount": Object { - "percentiles": Object { - "field": "transaction.experience.longtask.count", - "hdr": Object { - "number_of_significant_value_digits": 3, - }, - "percents": Array [ - 50, - ], + "aggs": Object { + "longTaskCount": Object { + "percentiles": Object { + "field": "transaction.experience.longtask.count", + "hdr": Object { + "number_of_significant_value_digits": 3, }, + "percents": Array [ + 50, + ], }, - "longTaskMax": Object { - "percentiles": Object { - "field": "transaction.experience.longtask.max", - "hdr": Object { - "number_of_significant_value_digits": 3, - }, - "percents": Array [ - 50, - ], + }, + "longTaskMax": Object { + "percentiles": Object { + "field": "transaction.experience.longtask.max", + "hdr": Object { + "number_of_significant_value_digits": 3, }, + "percents": Array [ + 50, + ], }, - "longTaskSum": Object { - "percentiles": Object { - "field": "transaction.experience.longtask.sum", - "hdr": Object { - "number_of_significant_value_digits": 3, - }, - "percents": Array [ - 50, - ], + }, + "longTaskSum": Object { + "percentiles": Object { + "field": "transaction.experience.longtask.sum", + "hdr": Object { + "number_of_significant_value_digits": 3, }, + "percents": Array [ + 50, + ], }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "term": Object { - "transaction.type": "page-load", - }, + }, + Object { + "term": Object { + "transaction.type": "page-load", }, - Object { - "terms": Object { - "processor.event": Array [ - "transaction", - ], - }, + }, + Object { + "terms": Object { + "processor.event": Array [ + "transaction", + ], }, - Object { - "exists": Object { - "field": "transaction.marks.navigationTiming.fetchStart", - }, + }, + Object { + "exists": Object { + "field": "transaction.marks.navigationTiming.fetchStart", }, - ], - "must_not": Array [], - }, + }, + ], + "must_not": Array [], }, - "size": 0, }, + "size": 0, } -`; \ No newline at end of file +`; diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/service_name_query.test.ts.snap b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/service_name_query.test.ts.snap index 2a3fbbd8b120f..1cf22e3f13d2c 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/service_name_query.test.ts.snap +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/__snapshots__/service_name_query.test.ts.snap @@ -2,49 +2,47 @@ exports[`serviceNameQuery fetches rum services 1`] = ` Object { - "body": Object { - "aggs": Object { - "services": Object { - "terms": Object { - "field": "service.name", - "size": 1000, - }, + "aggs": Object { + "services": Object { + "terms": Object { + "field": "service.name", + "size": 1000, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 0, - "lte": 50000, - }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 0, + "lte": 50000, }, }, - Object { - "term": Object { - "transaction.type": "page-load", - }, + }, + Object { + "term": Object { + "transaction.type": "page-load", }, - Object { - "terms": Object { - "processor.event": Array [ - "transaction", - ], - }, + }, + Object { + "terms": Object { + "processor.event": Array [ + "transaction", + ], }, - Object { - "exists": Object { - "field": "transaction.marks.navigationTiming.fetchStart", - }, + }, + Object { + "exists": Object { + "field": "transaction.marks.navigationTiming.fetchStart", }, - ], - "must_not": Array [], - }, + }, + ], + "must_not": Array [], }, - "size": 0, }, + "size": 0, } `; diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/client_metrics_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/client_metrics_query.ts index 1ab7eacb59855..b2250cb9f6589 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/client_metrics_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/client_metrics_query.ts @@ -30,31 +30,29 @@ export function clientMetricsQuery( }); const params = mergeProjection(projection, { - body: { - size: 0, - track_total_hits: true, - aggs: { - hasFetchStartField: { - filter: { - exists: { field: 'transaction.marks.navigationTiming.fetchStart' }, - }, - aggs: { - totalPageLoadDuration: { - percentiles: { - field: TRANSACTION_DURATION, - percents: [percentile], - hdr: { - number_of_significant_value_digits: 3, - }, + size: 0, + track_total_hits: true, + aggs: { + hasFetchStartField: { + filter: { + exists: { field: 'transaction.marks.navigationTiming.fetchStart' }, + }, + aggs: { + totalPageLoadDuration: { + percentiles: { + field: TRANSACTION_DURATION, + percents: [percentile], + hdr: { + number_of_significant_value_digits: 3, }, }, - backEnd: { - percentiles: { - field: TRANSACTION_TIME_TO_FIRST_BYTE, - percents: [percentile], - hdr: { - number_of_significant_value_digits: 3, - }, + }, + backEnd: { + percentiles: { + field: TRANSACTION_TIME_TO_FIRST_BYTE, + percents: [percentile], + hdr: { + number_of_significant_value_digits: 3, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts index 50ce9dcd1da6b..d2bbd0517780a 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts @@ -78,58 +78,56 @@ export function coreWebVitalsQuery( end, }); const params = mergeProjection(projection, { - body: { - size: 0, - query: { - bool: { - filter: [...projection.body.query.bool.filter], - }, + size: 0, + query: { + bool: { + filter: [...projection.query.bool.filter], }, - aggs: { - coreVitalPages: { - filter: { - exists: { - field: 'transaction.experience', - }, + }, + aggs: { + coreVitalPages: { + filter: { + exists: { + field: 'transaction.experience', }, }, - lcp: { - percentiles: { - field: LCP_FIELD, - percents: [percentile], - }, + }, + lcp: { + percentiles: { + field: LCP_FIELD, + percents: [percentile], }, - cls: { - percentiles: { - field: CLS_FIELD, - percents: [percentile], - }, + }, + cls: { + percentiles: { + field: CLS_FIELD, + percents: [percentile], }, - tbt: { - percentiles: { - field: TBT_FIELD, - percents: [percentile], - }, + }, + tbt: { + percentiles: { + field: TBT_FIELD, + percents: [percentile], }, - fcp: { - percentiles: { - field: FCP_FIELD, - percents: [percentile], - }, + }, + fcp: { + percentiles: { + field: FCP_FIELD, + percents: [percentile], }, - lcpRanks: { - percentile_ranks: { - field: LCP_FIELD, - values: [2500, 4000], - keyed: false, - }, + }, + lcpRanks: { + percentile_ranks: { + field: LCP_FIELD, + values: [2500, 4000], + keyed: false, }, - clsRanks: { - percentile_ranks: { - field: CLS_FIELD, - values: [0.1, 0.25], - keyed: false, - }, + }, + clsRanks: { + percentile_ranks: { + field: CLS_FIELD, + values: [0.1, 0.25], + keyed: false, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/environments_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/environments_query.ts index b65ea0bd7060b..9f722e2f8d864 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/environments_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/environments_query.ts @@ -43,43 +43,41 @@ export function getEnvironments({ end: number; }) { return { - body: { - size: 0, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: start, - lte: end, - format: 'epoch_millis', - }, + size: 0, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: start, + lte: end, + format: 'epoch_millis', }, }, - { - term: { - [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD, - }, + }, + { + term: { + [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD, }, - { - term: { - [PROCESSOR_EVENT]: 'transaction', - }, + }, + { + term: { + [PROCESSOR_EVENT]: 'transaction', }, - ...(serviceName === undefined || serviceName === null - ? [] - : [{ term: { [SERVICE_NAME]: serviceName } }]), - ], - }, - }, - aggs: { - environments: { - terms: { - field: SERVICE_ENVIRONMENT, - missing: ENVIRONMENT_NOT_DEFINED.value, - size, }, + ...(serviceName === undefined || serviceName === null + ? [] + : [{ term: { [SERVICE_NAME]: serviceName } }]), + ], + }, + }, + aggs: { + environments: { + terms: { + field: SERVICE_ENVIRONMENT, + missing: ENVIRONMENT_NOT_DEFINED.value, + size, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/has_rum_data_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/has_rum_data_query.ts index 05885d8931fec..47a09e7c14427 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/has_rum_data_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/has_rum_data_query.ts @@ -35,25 +35,23 @@ export function hasRumDataQuery({ end?: number; }) { return { - body: { - size: 0, - query: { - bool: { - filter: [ - { term: { [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD } }, - { term: { [PROCESSOR_EVENT]: 'transaction' } }, - ], - }, + size: 0, + query: { + bool: { + filter: [ + { term: { [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD } }, + { term: { [PROCESSOR_EVENT]: 'transaction' } }, + ], }, - aggs: { - services: { - filter: rangeQuery(start, end)[0], - aggs: { - mostTraffic: { - terms: { - field: SERVICE_NAME, - size: 1, - }, + }, + aggs: { + services: { + filter: rangeQuery(start, end)[0], + aggs: { + mostTraffic: { + terms: { + field: SERVICE_NAME, + size: 1, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts index cf0cd3df3d66f..f0772a4724f5f 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts @@ -49,27 +49,25 @@ export function inpQuery( end, }); return mergeProjection(projection, { - body: { - size: 0, - query: { - bool: { - filter: [...projection.body.query.bool.filter], - }, + size: 0, + query: { + bool: { + filter: [...projection.query.bool.filter], }, - aggs: { - inp: { - percentiles: { - field: INP_FIELD, - percents: [percentile], - }, + }, + aggs: { + inp: { + percentiles: { + field: INP_FIELD, + percents: [percentile], }, + }, - inpRanks: { - percentile_ranks: { - field: INP_FIELD, - values: [200, 500], - keyed: false, - }, + inpRanks: { + percentile_ranks: { + field: INP_FIELD, + values: [200, 500], + keyed: false, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/js_errors_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/js_errors_query.ts index cf5acb7d57d8c..3567e8f3f89fe 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/js_errors_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/js_errors_query.ts @@ -34,52 +34,50 @@ export function jsErrorsQuery( }); const params = mergeProjection(projection, { - body: { - size: 0, - track_total_hits: true, - aggs: { - totalErrorGroups: { - cardinality: { - field: ERROR_GROUP_ID, - }, + size: 0, + track_total_hits: true, + aggs: { + totalErrorGroups: { + cardinality: { + field: ERROR_GROUP_ID, }, - totalErrorPages: { - cardinality: { - field: TRANSACTION_ID, - }, + }, + totalErrorPages: { + cardinality: { + field: TRANSACTION_ID, + }, + }, + errors: { + terms: { + field: ERROR_GROUP_ID, + size: 500, }, - errors: { - terms: { - field: ERROR_GROUP_ID, - size: 500, + aggs: { + bucket_truncate: { + bucket_sort: { + size: pageSize, + from: pageIndex * pageSize, + }, }, - aggs: { - bucket_truncate: { - bucket_sort: { - size: pageSize, - from: pageIndex * pageSize, + impactedPages: { + filter: { + term: { + [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD, }, }, - impactedPages: { - filter: { - term: { - [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD, - }, - }, - aggs: { - pageCount: { - cardinality: { - field: TRANSACTION_ID, - }, + aggs: { + pageCount: { + cardinality: { + field: TRANSACTION_ID, }, }, }, - sample: { - top_hits: { - _source: [ERROR_EXC_MESSAGE, ERROR_EXC_TYPE, ERROR_GROUP_ID, '@timestamp'], - sort: [{ '@timestamp': 'desc' as const }], - size: 1, - }, + }, + sample: { + top_hits: { + _source: [ERROR_EXC_MESSAGE, ERROR_EXC_TYPE, ERROR_GROUP_ID, '@timestamp'], + sort: [{ '@timestamp': 'desc' as const }], + size: 1, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/long_task_metrics_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/long_task_metrics_query.ts index 4f965c970bd2f..d29094429dc01 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/long_task_metrics_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/long_task_metrics_query.ts @@ -30,34 +30,32 @@ export function longTaskMetricsQuery( }); const params = mergeProjection(projection, { - body: { - size: 0, - aggs: { - longTaskSum: { - percentiles: { - field: LONG_TASK_SUM_FIELD, - percents: [percentile], - hdr: { - number_of_significant_value_digits: 3, - }, + size: 0, + aggs: { + longTaskSum: { + percentiles: { + field: LONG_TASK_SUM_FIELD, + percents: [percentile], + hdr: { + number_of_significant_value_digits: 3, }, }, - longTaskCount: { - percentiles: { - field: LONG_TASK_COUNT_FIELD, - percents: [percentile], - hdr: { - number_of_significant_value_digits: 3, - }, + }, + longTaskCount: { + percentiles: { + field: LONG_TASK_COUNT_FIELD, + percents: [percentile], + hdr: { + number_of_significant_value_digits: 3, }, }, - longTaskMax: { - percentiles: { - field: LONG_TASK_MAX_FIELD, - percents: [percentile], - hdr: { - number_of_significant_value_digits: 3, - }, + }, + longTaskMax: { + percentiles: { + field: LONG_TASK_MAX_FIELD, + percents: [percentile], + hdr: { + number_of_significant_value_digits: 3, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/projections.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/projections.ts index 9cff5b78b8f92..8f5786d692b22 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/projections.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/projections.ts @@ -62,10 +62,8 @@ export function getRumPageLoadTransactionsProjection({ }; return { - body: { - query: { - bool, - }, + query: { + bool, }, }; } @@ -103,21 +101,17 @@ export function getRumPageExitTransactionsProjection({ }; return { - body: { - query: { - bool, - }, + query: { + bool, }, }; } export interface RumErrorsProjection { - body: { - query: { - bool: { - filter: QueryDslQueryContainer[]; - must_not: QueryDslQueryContainer[]; - }; + query: { + bool: { + filter: QueryDslQueryContainer[]; + must_not: QueryDslQueryContainer[]; }; }; } @@ -134,30 +128,28 @@ export function getRumErrorsProjection({ end: number; }): RumErrorsProjection { return { - body: { - query: { - bool: { - filter: [ - ...rangeQuery(start, end), - { term: { [AGENT_NAME]: 'rum-js' } }, - { - terms: { - [PROCESSOR_EVENT]: [ProcessorEvent.error], - }, + query: { + bool: { + filter: [ + ...rangeQuery(start, end), + { term: { [AGENT_NAME]: 'rum-js' } }, + { + terms: { + [PROCESSOR_EVENT]: [ProcessorEvent.error], }, - ...getEsFilter(setup.uiFilters), - ...(urlQuery - ? [ - { - wildcard: { - 'url.full': `*${urlQuery}*`, - }, + }, + ...getEsFilter(setup.uiFilters), + ...(urlQuery + ? [ + { + wildcard: { + 'url.full': `*${urlQuery}*`, }, - ] - : []), - ], - must_not: [...getEsFilter(setup.uiFilters, true)], - }, + }, + ] + : []), + ], + must_not: [...getEsFilter(setup.uiFilters, true)], }, }, }; diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/range_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/range_query.ts index 3ad1aec5a560d..e68af25192c1a 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/range_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/range_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export function rangeQuery( start?: number, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts index d267299fcf596..a33c24f359343 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts @@ -18,17 +18,15 @@ export function serviceNameQuery(start: number, end: number, uiFilters?: UxUIFil end, }); const params = mergeProjection(projection, { - body: { - size: 0, - query: { - bool: projection.body.query.bool, - }, - aggs: { - services: { - terms: { - field: SERVICE_NAME, - size: 1000, - }, + size: 0, + query: { + bool: projection.query.bool, + }, + aggs: { + services: { + terms: { + field: SERVICE_NAME, + size: 1000, }, }, }, diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/url_search_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/url_search_query.ts index 56a3dac2181f1..2fad833fafc27 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/url_search_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/url_search_query.ts @@ -21,25 +21,23 @@ export function urlSearchQuery(restFilters: any, uxQuery: any, searchValue: stri end: callDateMath(uxQuery?.end), }); const params = mergeProjection(projection, { - body: { - size: 0, - aggs: { - totalUrls: { - cardinality: { - field: TRANSACTION_URL, - }, + size: 0, + aggs: { + totalUrls: { + cardinality: { + field: TRANSACTION_URL, }, - urls: { - terms: { - field: TRANSACTION_URL, - size: 10, - }, - aggs: { - medianPLD: { - percentiles: { - field: TRANSACTION_DURATION, - percents: [Number(uxQuery?.percentile)], - }, + }, + urls: { + terms: { + field: TRANSACTION_URL, + size: 10, + }, + aggs: { + medianPLD: { + percentiles: { + field: TRANSACTION_DURATION, + percents: [Number(uxQuery?.percentile)], }, }, }, diff --git a/x-pack/solutions/search/plugins/enterprise_search/public/applications/enterprise_search_content/__mocks__/ml_models.mock.ts b/x-pack/solutions/search/plugins/enterprise_search/public/applications/enterprise_search_content/__mocks__/ml_models.mock.ts index 8fe40dfc5c7a8..6be52ba69d59d 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/public/applications/enterprise_search_content/__mocks__/ml_models.mock.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/public/applications/enterprise_search_content/__mocks__/ml_models.mock.ts @@ -52,7 +52,6 @@ export const textClassificationModel: TrainedModelConfigResponse = { tokenization: { roberta: { add_prefix_space: false, - // @ts-expect-error upgrade typescript v5.1.6 do_lower_case: false, max_sequence_length: 512, span: -1, @@ -73,7 +72,11 @@ export const textClassificationModel: TrainedModelConfigResponse = { export const textExpansionModel: TrainedModelConfigResponse = { inference_config: { - text_expansion: {}, + text_expansion: { + vocabulary: { + index: 'vocabulary-index', + }, + }, }, input: { field_names: ['text_field'], diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/get_ml_inference_errors.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/get_ml_inference_errors.ts index 1556b478de21e..572cbb3c5b707 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/get_ml_inference_errors.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/get_ml_inference_errors.ts @@ -38,27 +38,25 @@ export const getMlInferenceErrors = async ( } >({ index: indexName, - body: { - aggs: { - errors: { - terms: { - field: '_ingest.inference_errors.message.enum', - order: { - max_error_timestamp: 'desc', - }, - size: 20, + aggs: { + errors: { + terms: { + field: '_ingest.inference_errors.message.enum', + order: { + max_error_timestamp: 'desc', }, - aggs: { - max_error_timestamp: { - max: { - field: '_ingest.inference_errors.timestamp', - }, + size: 20, + }, + aggs: { + max_error_timestamp: { + max: { + field: '_ingest.inference_errors.timestamp', }, }, }, }, - size: 0, }, + size: 0, }); const errorBuckets = searchResult.aggregations?.errors.buckets; diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.test.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.test.ts index bb9d7395c58e5..06e6294a9dd2d 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.test.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.test.ts @@ -24,7 +24,11 @@ describe('updateMlInferenceMappings', () => { trained_model_configs: [ { inference_config: { - text_expansion: {}, + text_expansion: { + vocabulary: { + index: 'an-index-vocabulary', + }, + }, }, input: { field_names: [], diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/fetch_ml_models.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/fetch_ml_models.ts index 889b7bb1b89e1..793022d3e3fe1 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/fetch_ml_models.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/fetch_ml_models.ts @@ -137,11 +137,13 @@ const getModel = (modelConfig: MlTrainedModelConfig, modelStats?: MlTrainedModel // Enrich deployment stats if (modelStats && modelStats.deployment_stats) { model.hasStats = true; - model.deploymentState = getDeploymentState(modelStats.deployment_stats.allocation_status.state); - model.nodeAllocationCount = modelStats.deployment_stats.allocation_status.allocation_count; + model.deploymentState = getDeploymentState( + modelStats.deployment_stats.allocation_status?.state! + ); + model.nodeAllocationCount = modelStats.deployment_stats.allocation_status?.allocation_count!; model.targetAllocationCount = - modelStats.deployment_stats.allocation_status.target_allocation_count; - model.threadsPerAllocation = modelStats.deployment_stats.threads_per_allocation; + modelStats.deployment_stats.allocation_status?.target_allocation_count!; + model.threadsPerAllocation = modelStats.deployment_stats.threads_per_allocation!; model.startTime = modelStats.deployment_stats.start_time; } else if (model.modelId === LANG_IDENT_MODEL_ID) { model.deploymentState = MlModelDeploymentState.FullyAllocated; diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.ts index 494cb925bf77f..40df33ef75726 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.ts @@ -70,11 +70,11 @@ export const getMlModelDeploymentStatus = async ( const modelDeployment = modelStatsResponse.trained_model_stats[0].deployment_stats; return { - deploymentState: getMlModelDeploymentStateForStatus(modelDeployment?.allocation_status.state), + deploymentState: getMlModelDeploymentStateForStatus(modelDeployment?.allocation_status?.state), modelId: modelName, - nodeAllocationCount: modelDeployment?.allocation_status.allocation_count || 0, + nodeAllocationCount: modelDeployment?.allocation_status?.allocation_count || 0, startTime: modelDeployment?.start_time || 0, - targetAllocationCount: modelDeployment?.allocation_status.target_allocation_count || 0, + targetAllocationCount: modelDeployment?.allocation_status?.target_allocation_count || 0, threadsPerAllocation: modelDeployment?.threads_per_allocation || 0, }; }; diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/routes/enterprise_search/search_applications.ts b/x-pack/solutions/search/plugins/enterprise_search/server/routes/enterprise_search/search_applications.ts index 61bfc6172c5de..39b507a5abae7 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/routes/enterprise_search/search_applications.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/routes/enterprise_search/search_applications.ts @@ -131,6 +131,7 @@ export function registerSearchApplicationsRoutes({ log, router }: RouteDependenc name: request.params.engine_name, search_application: { indices: request.body.indices, + // @ts-expect-error elasticsearch@9.0.0 has this parameter been renamed to analytics_collection_name? name: request.params.engine_name, template: script == null diff --git a/x-pack/solutions/search/plugins/search_indices/public/components/index_documents/add_documents_code_example.test.tsx b/x-pack/solutions/search/plugins/search_indices/public/components/index_documents/add_documents_code_example.test.tsx index 4a04d63de93c5..ab5fe979146d8 100644 --- a/x-pack/solutions/search/plugins/search_indices/public/components/index_documents/add_documents_code_example.test.tsx +++ b/x-pack/solutions/search/plugins/search_indices/public/components/index_documents/add_documents_code_example.test.tsx @@ -95,7 +95,12 @@ describe('AddDocumentsCodeExample', () => { it('pass examples when mapping is default with extra vector fields', () => { const indexName = 'test-index'; const mappingProperties: Record = { - vector: { type: 'dense_vector', dims: 3, similarity: 'extra' }, + vector: { + type: 'dense_vector', + dims: 3, + // @ts-expect-error `extra` is not a valid MappingDenseVectorSimilarity + similarity: 'extra', + }, text: { type: 'text' }, }; diff --git a/x-pack/solutions/search/plugins/search_playground/server/lib/conversational_chain.ts b/x-pack/solutions/search/plugins/search_playground/server/lib/conversational_chain.ts index e63457f23d4d6..7028aad64e05c 100644 --- a/x-pack/solutions/search/plugins/search_playground/server/lib/conversational_chain.ts +++ b/x-pack/solutions/search/plugins/search_playground/server/lib/conversational_chain.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { Document } from '@langchain/core/documents'; import { ChatPromptTemplate, diff --git a/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.test.ts b/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.test.ts index 7c81f1760f065..fe6360ea62285 100644 --- a/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.test.ts +++ b/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.test.ts @@ -493,20 +493,18 @@ describe('fetch_query_source_fields', () => { await fetchFields(client, indices); expect(client.asCurrentUser.search).toHaveBeenCalledWith({ index: 'search-example-main', - body: { - size: 0, - aggs: { - 'page_content_e5_embbeding.model_id': { - terms: { - field: 'page_content_e5_embbeding.model_id.keyword', - size: 1, - }, + size: 0, + aggs: { + 'page_content_e5_embbeding.model_id': { + terms: { + field: 'page_content_e5_embbeding.model_id.keyword', + size: 1, }, - 'page_content_ner.model_id': { - terms: { - field: 'page_content_ner.model_id', - size: 1, - }, + }, + 'page_content_ner.model_id': { + terms: { + field: 'page_content_ner.model_id', + size: 1, }, }, }, @@ -531,14 +529,12 @@ describe('fetch_query_source_fields', () => { const response = await fetchFields(client, indices); expect(client.asCurrentUser.search).toHaveBeenCalledWith({ index: 'search-test-e5', - body: { - size: 0, - aggs: { - 'ml.inference.body_content.model_id': { - terms: { - field: 'ml.inference.body_content.model_id.enum', - size: 1, - }, + size: 0, + aggs: { + 'ml.inference.body_content.model_id': { + terms: { + field: 'ml.inference.body_content.model_id.enum', + size: 1, }, }, }, @@ -579,14 +575,12 @@ describe('fetch_query_source_fields', () => { await fetchFields(client, indices); expect(client.asCurrentUser.search).toHaveBeenCalledWith({ index: 'index', - body: { - size: 0, - aggs: { - model_id: { - terms: { - field: 'model_id.keyword', - size: 1, - }, + size: 0, + aggs: { + model_id: { + terms: { + field: 'model_id.keyword', + size: 1, }, }, }, diff --git a/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.ts b/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.ts index 154261a019528..67cb136a97b23 100644 --- a/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.ts +++ b/x-pack/solutions/search/plugins/search_playground/server/lib/fetch_query_source_fields.ts @@ -89,21 +89,19 @@ export const fetchFields = async ( index, doc: await client.asCurrentUser.search({ index, - body: { - size: 0, - aggs: modelIdFields.reduce( - (sum, modelIdField) => ({ - ...sum, - [modelIdField.path]: { - terms: { - field: modelIdField.aggField, - size: 1, - }, + size: 0, + aggs: modelIdFields.reduce( + (sum, modelIdField) => ({ + ...sum, + [modelIdField.path]: { + terms: { + field: modelIdField.aggField, + size: 1, }, - }), - {} - ), - }, + }, + }), + {} + ), }), mapping: await client.asCurrentUser.indices.getMapping({ index }), })) diff --git a/x-pack/solutions/search/plugins/search_synonyms/server/lib/put_synonyms_set.ts b/x-pack/solutions/search/plugins/search_synonyms/server/lib/put_synonyms_set.ts index 422e1f937e3d3..56f5a5646ef68 100644 --- a/x-pack/solutions/search/plugins/search_synonyms/server/lib/put_synonyms_set.ts +++ b/x-pack/solutions/search/plugins/search_synonyms/server/lib/put_synonyms_set.ts @@ -14,8 +14,6 @@ export const putSynonymsSet = async ( ): Promise => { return client.synonyms.putSynonym({ id: synonymsSetId, - body: { - synonyms_set: [], - }, + synonyms_set: [], }); }; diff --git a/x-pack/solutions/search/plugins/serverless_search/server/routes/connectors_routes.ts b/x-pack/solutions/search/plugins/serverless_search/server/routes/connectors_routes.ts index 55571da5bdda4..d9fc46f04a0c3 100644 --- a/x-pack/solutions/search/plugins/serverless_search/server/routes/connectors_routes.ts +++ b/x-pack/solutions/search/plugins/serverless_search/server/routes/connectors_routes.ts @@ -34,9 +34,7 @@ export const registerConnectorsRoutes = ({ logger, http, router }: RouteDependen errorHandler(logger)(async (context, request, response) => { const { client } = (await context.core).elasticsearch; const privileges = await client.asCurrentUser.security.hasPrivileges({ - body: { - cluster: ['manage_connector', 'monitor_connector'], - }, + cluster: ['manage_connector', 'monitor_connector'], }); const canManageConnectors = privileges.cluster.manage_connector; const canReadConnectors = privileges.cluster.monitor_connector; diff --git a/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.test.ts b/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.test.ts index 35112e96ecb09..a8da9cf65ba2a 100644 --- a/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.test.ts +++ b/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.test.ts @@ -48,7 +48,7 @@ describe('updateDataStreams', () => { expect(esClient.indices.putSettings).toHaveBeenCalledWith({ index: dataStreamName, - body: { 'index.mapping.total_fields.limit': totalFieldsLimit }, + settings: { 'index.mapping.total_fields.limit': totalFieldsLimit }, }); expect(esClient.indices.simulateIndexTemplate).toHaveBeenCalledWith({ name: dataStreamName, @@ -160,7 +160,7 @@ describe('createOrUpdateDataStream', () => { expect(esClient.indices.putSettings).toHaveBeenCalledWith({ index: name, - body: { 'index.mapping.total_fields.limit': totalFieldsLimit }, + settings: { 'index.mapping.total_fields.limit': totalFieldsLimit }, }); expect(esClient.indices.simulateIndexTemplate).toHaveBeenCalledWith({ name, diff --git a/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.ts b/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.ts index 50aa6e5f9574b..4698cbb75b7a2 100644 --- a/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.ts +++ b/x-pack/solutions/security/packages/data-stream-adapter/src/create_or_update_data_stream.ts @@ -5,8 +5,10 @@ * 2.0. */ -import type { IndicesDataStream } from '@elastic/elasticsearch/lib/api/types'; -import type { IndicesSimulateIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { + IndicesDataStream, + IndicesSimulateIndexTemplateResponse, +} from '@elastic/elasticsearch/lib/api/types'; import type { Logger, ElasticsearchClient } from '@kbn/core/server'; import { get } from 'lodash'; import { retryTransientEsErrors } from '@kbn/index-adapter'; @@ -36,10 +38,11 @@ const updateTotalFieldLimitSetting = async ({ logger.debug(`Updating total field limit setting for ${indexName} data stream.`); try { - const body = { 'index.mapping.total_fields.limit': totalFieldsLimit }; - await retryTransientEsErrors(() => esClient.indices.putSettings({ index: indexName, body }), { - logger, - }); + const settings = { 'index.mapping.total_fields.limit': totalFieldsLimit }; + await retryTransientEsErrors( + () => esClient.indices.putSettings({ index: indexName, settings }), + { logger } + ); } catch (err) { logger.error( `Failed to PUT index.mapping.total_fields.limit settings for ${indexName}: ${err.message}` @@ -80,6 +83,7 @@ const updateMapping = async ({ logger, esClient, indexName, writeIndexOnly }: Up () => esClient.indices.putMapping({ index: indexName, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 body: simulatedMapping, write_index_only: writeIndexOnly, }), diff --git a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.test.ts b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.test.ts index a2caebfc4e359..c274805341232 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.test.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.test.ts @@ -149,14 +149,12 @@ describe('createOrUpdateComponentTemplate', () => { expect(clusterClient.indices.putIndexTemplate).toHaveBeenCalledTimes(1); expect(clusterClient.indices.putIndexTemplate).toHaveBeenCalledWith({ name: existingIndexTemplate.name, - body: { - ...existingIndexTemplate.index_template, - template: { - ...existingIndexTemplate.index_template.template, - settings: { - ...existingIndexTemplate.index_template.template?.settings, - 'index.mapping.total_fields.limit': 2500, - }, + ...existingIndexTemplate.index_template, + template: { + ...existingIndexTemplate.index_template.template, + settings: { + ...existingIndexTemplate.index_template.template?.settings, + 'index.mapping.total_fields.limit': 2500, }, }, }); @@ -226,14 +224,12 @@ describe('createOrUpdateComponentTemplate', () => { expect(clusterClient.indices.putIndexTemplate).toHaveBeenCalledTimes(1); expect(clusterClient.indices.putIndexTemplate).toHaveBeenCalledWith({ name: existingIndexTemplate.name, - body: { - ...existingIndexTemplate.index_template, - template: { - ...existingIndexTemplate.index_template.template, - settings: { - ...existingIndexTemplate.index_template.template?.settings, - 'index.mapping.total_fields.limit': 2500, - }, + ...existingIndexTemplate.index_template, + template: { + ...existingIndexTemplate.index_template.template, + settings: { + ...existingIndexTemplate.index_template.template?.settings, + 'index.mapping.total_fields.limit': 2500, }, }, }); diff --git a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.ts b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.ts index ca1ddebe0571b..ec409f667229b 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_component_template.ts @@ -8,8 +8,7 @@ import type { ClusterPutComponentTemplateRequest, IndicesGetIndexTemplateIndexTemplateItem, - IndicesPutIndexTemplateRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { Logger, ElasticsearchClient } from '@kbn/core/server'; import { asyncForEach } from '@kbn/std'; import { retryTransientEsErrors } from './retry_transient_es_errors'; @@ -44,16 +43,19 @@ const putIndexTemplateTotalFieldsLimitUsingComponentTemplate = async ( () => esClient.indices.putIndexTemplate({ name: template.name, - body: { - ...template.index_template, - template: { - ...template.index_template.template, - settings: { - ...template.index_template.template?.settings, - 'index.mapping.total_fields.limit': totalFieldsLimit, - }, + ...template.index_template, + template: { + ...template.index_template.template, + settings: { + ...template.index_template.template?.settings, + 'index.mapping.total_fields.limit': totalFieldsLimit, }, - } as IndicesPutIndexTemplateRequest['body'], + }, + // GET brings string | string[] | undefined but this PUT expects string[] + ignore_missing_component_templates: template.index_template + .ignore_missing_component_templates + ? [template.index_template.ignore_missing_component_templates].flat() + : undefined, }), { logger } ); diff --git a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.test.ts b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.test.ts index 22d126782f68c..36a00dc358570 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.test.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.test.ts @@ -43,7 +43,7 @@ describe('updateIndices', () => { expect(esClient.indices.putSettings).toHaveBeenCalledWith({ index: indexName, - body: { 'index.mapping.total_fields.limit': totalFieldsLimit }, + settings: { 'index.mapping.total_fields.limit': totalFieldsLimit }, }); expect(esClient.indices.simulateIndexTemplate).toHaveBeenCalledWith({ name: indexName, @@ -151,7 +151,7 @@ describe('createOrUpdateIndex', () => { expect(esClient.indices.putSettings).toHaveBeenCalledWith({ index: name, - body: { 'index.mapping.total_fields.limit': totalFieldsLimit }, + settings: { 'index.mapping.total_fields.limit': totalFieldsLimit }, }); expect(esClient.indices.simulateIndexTemplate).toHaveBeenCalledWith({ name, diff --git a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.ts b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.ts index 42abb38fb858d..a6b2eeaaa436d 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index.ts @@ -5,8 +5,10 @@ * 2.0. */ -import type { IndexName } from '@elastic/elasticsearch/lib/api/types'; -import type { IndicesSimulateIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { + IndexName, + IndicesSimulateIndexTemplateResponse, +} from '@elastic/elasticsearch/lib/api/types'; import type { Logger, ElasticsearchClient } from '@kbn/core/server'; import { get } from 'lodash'; import { retryTransientEsErrors } from './retry_transient_es_errors'; @@ -36,10 +38,11 @@ const updateTotalFieldLimitSetting = async ({ logger.debug(`Updating total field limit setting for ${indexName} data stream.`); try { - const body = { 'index.mapping.total_fields.limit': totalFieldsLimit }; - await retryTransientEsErrors(() => esClient.indices.putSettings({ index: indexName, body }), { - logger, - }); + const settings = { 'index.mapping.total_fields.limit': totalFieldsLimit }; + await retryTransientEsErrors( + () => esClient.indices.putSettings({ index: indexName, settings }), + { logger } + ); } catch (err) { logger.error( `Failed to PUT index.mapping.total_fields.limit settings for ${indexName}: ${err.message}` @@ -80,6 +83,7 @@ const updateMapping = async ({ logger, esClient, indexName, writeIndexOnly }: Up () => esClient.indices.putMapping({ index: indexName, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 body: simulatedMapping, write_index_only: writeIndexOnly, }), diff --git a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.test.ts b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.test.ts index eb85b0931f9ef..6aaa672895f1e 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.test.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.test.ts @@ -15,44 +15,42 @@ const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; const getIndexTemplate = (namespace: string = 'default', useDataStream: boolean = false) => ({ name: `.alerts-test.alerts-${namespace}-index-template`, - body: { - _meta: { - kibana: { - version: '8.6.1', - }, - managed: true, - namespace, + _meta: { + kibana: { + version: '8.6.1', }, - composed_of: ['mappings1', 'framework-mappings'], - index_patterns: [`.internal.alerts-test.alerts-${namespace}-*`], - template: { - mappings: { - _meta: { - kibana: { - version: '8.6.1', - }, - managed: true, - namespace, + managed: true, + namespace, + }, + composed_of: ['mappings1', 'framework-mappings'], + index_patterns: [`.internal.alerts-test.alerts-${namespace}-*`], + template: { + mappings: { + _meta: { + kibana: { + version: '8.6.1', }, - dynamic: false, - }, - settings: { - auto_expand_replicas: '0-1', - hidden: true, - ...(useDataStream - ? {} - : { - 'index.lifecycle': { - name: 'test-ilm-policy', - rollover_alias: `.alerts-test.alerts-${namespace}`, - }, - }), - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': 2500, + managed: true, + namespace, }, + dynamic: false, + }, + settings: { + auto_expand_replicas: '0-1', + hidden: true, + ...(useDataStream + ? {} + : { + 'index.lifecycle': { + name: 'test-ilm-policy', + rollover_alias: `.alerts-test.alerts-${namespace}`, + }, + }), + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': 2500, }, - priority: namespace.length, }, + priority: namespace.length, }); const simulateTemplateResponse = { diff --git a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.ts b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.ts index d7e4b25771b86..0567f8eef35fd 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/create_or_update_index_template.ts @@ -8,7 +8,7 @@ import type { IndicesPutIndexTemplateRequest, MappingTypeMapping, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { Logger, ElasticsearchClient } from '@kbn/core/server'; import { isEmpty } from 'lodash/fp'; import { retryTransientEsErrors } from './retry_transient_es_errors'; diff --git a/x-pack/solutions/security/packages/index-adapter/src/field_maps/mapping_from_field_map.ts b/x-pack/solutions/security/packages/index-adapter/src/field_maps/mapping_from_field_map.ts index c40dcbef695c5..56fc697e7c8f1 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/field_maps/mapping_from_field_map.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/field_maps/mapping_from_field_map.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { set } from '@kbn/safer-lodash-set'; import type { FieldMap, MultiField } from './types'; diff --git a/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.test.ts b/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.test.ts index 2067d17e5cb36..52f3ed9945e84 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.test.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.test.ts @@ -21,42 +21,40 @@ describe('getIndexTemplate', () => { expect(indexTemplate).toEqual({ name: defaultParams.name, - body: { - index_patterns: defaultParams.indexPatterns, - composed_of: defaultParams.componentTemplateRefs, - template: { - settings: { - hidden: true, - auto_expand_replicas: '0-1', - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': defaultParams.totalFieldsLimit, - }, - mappings: { - dynamic: false, - _meta: { - kibana: { - version: defaultParams.kibanaVersion, - }, - managed: true, - namespace: 'default', + index_patterns: defaultParams.indexPatterns, + composed_of: defaultParams.componentTemplateRefs, + template: { + settings: { + hidden: true, + auto_expand_replicas: '0-1', + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': defaultParams.totalFieldsLimit, + }, + mappings: { + dynamic: false, + _meta: { + kibana: { + version: defaultParams.kibanaVersion, }, + managed: true, + namespace: 'default', }, }, - _meta: { - kibana: { - version: defaultParams.kibanaVersion, - }, - managed: true, - namespace: 'default', + }, + _meta: { + kibana: { + version: defaultParams.kibanaVersion, }, - priority: 7, + managed: true, + namespace: 'default', }, + priority: 7, }); }); it('should create data stream index template with given parameters and defaults', () => { const indexTemplate = getIndexTemplate({ ...defaultParams, isDataStream: true }); - expect(indexTemplate.body).toEqual( + expect(indexTemplate).toEqual( expect.objectContaining({ data_stream: { hidden: true }, }) @@ -64,19 +62,19 @@ describe('getIndexTemplate', () => { }); it('should create not hidden index template', () => { - const { body } = getIndexTemplate({ ...defaultParams, isDataStream: true, hidden: false }); + const body = getIndexTemplate({ ...defaultParams, isDataStream: true, hidden: false }); expect(body?.data_stream?.hidden).toEqual(false); expect(body?.template?.settings?.hidden).toEqual(false); }); it('should create index template with custom namespace', () => { - const { body } = getIndexTemplate({ ...defaultParams, namespace: 'custom-namespace' }); + const body = getIndexTemplate({ ...defaultParams, namespace: 'custom-namespace' }); expect(body?._meta?.namespace).toEqual('custom-namespace'); expect(body?.priority).toEqual(16); }); it('should create index template with template overrides', () => { - const { body } = getIndexTemplate({ + const body = getIndexTemplate({ ...defaultParams, template: { settings: { diff --git a/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.ts b/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.ts index dbe958dc019d7..80e323bd364ab 100644 --- a/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.ts +++ b/x-pack/solutions/security/packages/index-adapter/src/resource_installer_utils.ts @@ -8,8 +8,6 @@ import type { IndicesPutIndexTemplateRequest, Metadata, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { ClusterPutComponentTemplateRequest, IndicesIndexSettings, IndicesPutIndexTemplateIndexTemplateMapping, @@ -78,30 +76,28 @@ export const getIndexTemplate = ({ return { name, - body: { - ...(isDataStream && { data_stream: { hidden } }), - index_patterns: indexPatterns, - composed_of: componentTemplateRefs, - template: { - ...template, - settings: { - hidden, - auto_expand_replicas: '0-1', - 'index.mapping.ignore_malformed': true, - 'index.mapping.total_fields.limit': totalFieldsLimit, - ...template.settings, - }, - mappings: { - dynamic: false, - _meta: indexMetadata, - ...template.mappings, - }, + ...(isDataStream && { data_stream: { hidden } }), + index_patterns: indexPatterns, + composed_of: componentTemplateRefs, + template: { + ...template, + settings: { + hidden, + auto_expand_replicas: '0-1', + 'index.mapping.ignore_malformed': true, + 'index.mapping.total_fields.limit': totalFieldsLimit, + ...template.settings, + }, + mappings: { + dynamic: false, + _meta: indexMetadata, + ...template.mappings, }, - _meta: indexMetadata, - - // By setting the priority to namespace.length, we ensure that if one namespace is a prefix of another namespace - // then newly created indices will use the matching template with the *longest* namespace - priority: namespace.length, }, + _meta: indexMetadata, + + // By setting the priority to namespace.length, we ensure that if one namespace is a prefix of another namespace + // then newly created indices will use the matching template with the *longest* namespace + priority: namespace.length, }; }; diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/types.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/types.ts index 738df0265a9c9..5c3eec8a1dd33 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/types.ts +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/types.ts @@ -23,7 +23,7 @@ import type { UsageCollectionStart } from '@kbn/usage-collection-plugin/public'; import { SharePluginStart } from '@kbn/share-plugin/public'; import { SpacesPluginStart } from '@kbn/spaces-plugin/public'; import { CspFinding } from '@kbn/cloud-security-posture-common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types'; import type { BoolQuery } from '@kbn/es-query'; diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.test.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.test.ts index 8bf53fcddebe4..634a27edad72f 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.test.ts +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { AggregationBuckets, getVulnerabilitiesAggregationCount, diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.ts b/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.ts index 324549098ed17..14ea869312562 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.ts +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/public/src/utils/hooks_utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { buildMutedRulesFilter, CDR_MISCONFIGURATIONS_INDEX_PATTERN, diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts index e31ce74ee945b..294c480c1ed3b 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import type { CspFinding } from '@kbn/cloud-security-posture-common'; import { isArray } from 'lodash'; import { http, HttpResponse } from 'msw'; diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/latest_findings/use_latest_findings.ts b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/latest_findings/use_latest_findings.ts index 33ec005b33750..9800990a38e4b 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/latest_findings/use_latest_findings.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/latest_findings/use_latest_findings.ts @@ -8,7 +8,7 @@ import { useInfiniteQuery } from '@tanstack/react-query'; import { number } from 'io-ts'; import { lastValueFrom } from 'rxjs'; import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { buildDataTableRecord } from '@kbn/discover-utils'; import { EsHitRecord } from '@kbn/discover-utils/types'; import { showErrorToast } from '@kbn/cloud-security-posture'; diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/server/create_indices/create_indices.ts b/x-pack/solutions/security/plugins/cloud_security_posture/server/create_indices/create_indices.ts index 7a1f49e2ac01f..e60852d4b5a28 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/server/create_indices/create_indices.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/server/create_indices/create_indices.ts @@ -243,20 +243,18 @@ const updateIndexTemplate = async ( try { await esClient.indices.putIndexTemplate({ name: indexTemplateName, - body: { - index_patterns: indexPattern, - priority: 500, - template: { - mappings: template?.mappings, - settings, - aliases: template?.aliases, - }, - _meta, - composed_of: composedOf.filter((ct) => ct !== STACK_COMPONENT_TEMPLATE_LOGS_SETTINGS), - ignore_missing_component_templates: composedOf.filter((templateName) => - templateName.endsWith('@custom') - ), + index_patterns: indexPattern, + priority: 500, + template: { + mappings: template?.mappings, + settings, + aliases: template?.aliases, }, + _meta, + composed_of: composedOf.filter((ct) => ct !== STACK_COMPONENT_TEMPLATE_LOGS_SETTINGS), + ignore_missing_component_templates: composedOf.filter((templateName) => + templateName.endsWith('@custom') + ), }); logger.info(`Updated index template successfully [Name: ${indexTemplateName}]`); diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/vulnerabilities_dashboard/get_vulnerabilities_trend.ts b/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/vulnerabilities_dashboard/get_vulnerabilities_trend.ts index 5a619b125deab..d37a039a8bcbe 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/vulnerabilities_dashboard/get_vulnerabilities_trend.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/server/routes/vulnerabilities_dashboard/get_vulnerabilities_trend.ts @@ -53,9 +53,9 @@ export const getVulnTrendsQuery = () => ({ vuln_severity_per_day: { date_histogram: { field: '@timestamp', - calendar_interval: '1d', + calendar_interval: '1d' as const, order: { - _key: 'asc', + _key: 'asc' as const, }, }, aggs: { @@ -65,7 +65,7 @@ export const getVulnTrendsQuery = () => ({ sort: [ { '@timestamp': { - order: 'desc', + order: 'desc' as const, }, }, ], diff --git a/x-pack/solutions/security/plugins/ecs_data_quality_dashboard/server/routes/results/get_index_results_latest.ts b/x-pack/solutions/security/plugins/ecs_data_quality_dashboard/server/routes/results/get_index_results_latest.ts index f7d1d5eed74cc..4ba7199d5216b 100644 --- a/x-pack/solutions/security/plugins/ecs_data_quality_dashboard/server/routes/results/get_index_results_latest.ts +++ b/x-pack/solutions/security/plugins/ecs_data_quality_dashboard/server/routes/results/get_index_results_latest.ts @@ -23,7 +23,9 @@ export const getQuery = (indexName: string[]) => ({ aggs: { latest: { terms: { field: 'indexName', size: 10000 }, // big enough to get all indexNames, but under `index.max_terms_count` (default 65536) - aggs: { latest_doc: { top_hits: { size: 1, sort: [{ '@timestamp': { order: 'desc' } }] } } }, + aggs: { + latest_doc: { top_hits: { size: 1, sort: [{ '@timestamp': { order: 'desc' as const } }] } }, + }, }, }, }); diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/anonymization_fields_schema.mock.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/anonymization_fields_schema.mock.ts index 73d47d96be492..2202809749ea0 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/anonymization_fields_schema.mock.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/anonymization_fields_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { AnonymizationFieldCreateProps, AnonymizationFieldResponse, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/attack_discovery_schema.mock.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/attack_discovery_schema.mock.ts index ee54e9c451ea2..c338bb3135617 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/attack_discovery_schema.mock.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/attack_discovery_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EsAttackDiscoverySchema } from '../lib/attack_discovery/persistence/types'; export const getAttackDiscoverySearchEsMock = () => { diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/conversations_schema.mock.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/conversations_schema.mock.ts index 278dfc9fe829b..0adcd8d763d2a 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/conversations_schema.mock.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/conversations_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { AppendConversationMessageRequestBody, PerformBulkActionRequestBody, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/defend_insights_schema.mock.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/defend_insights_schema.mock.ts index d25b8bb09b13d..474f456d4e8fa 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/defend_insights_schema.mock.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/defend_insights_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DefendInsightStatus, DefendInsightType } from '@kbn/elastic-assistant-common'; import type { EsDefendInsightSchema } from '../ai_assistant_data_clients/defend_insights/types'; diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/knowledge_base_entry_schema.mock.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/knowledge_base_entry_schema.mock.ts index 8171dd2b39249..c788f85b5cdcc 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/knowledge_base_entry_schema.mock.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/knowledge_base_entry_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { KnowledgeBaseEntryCreateProps, KnowledgeBaseEntryResponse, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/prompts_schema.mock.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/prompts_schema.mock.ts index 4939a6608e618..9717a24acd2e3 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/prompts_schema.mock.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/prompts_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EsPromptsSchema } from '../ai_assistant_data_clients/prompts/types'; import { PerformPromptsBulkActionRequestBody, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/response.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/response.ts index b7ab289d0f270..2345ed60540a2 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/response.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/__mocks__/response.ts @@ -7,7 +7,7 @@ import { httpServerMock } from '@kbn/core/server/mocks'; import { getConversationSearchEsMock } from './conversations_schema.mock'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EsConversationSchema } from '../ai_assistant_data_clients/conversations/types'; import { FindResponse } from '../ai_assistant_data_clients/find'; import { ConversationResponse } from '@kbn/elastic-assistant-common'; diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/anonymization_fields/helpers.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/anonymization_fields/helpers.ts index 0f577df4e56e1..fe075e540f8d0 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/anonymization_fields/helpers.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/anonymization_fields/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { AnonymizationFieldCreateProps, AnonymizationFieldResponse, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/create_conversation.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/create_conversation.ts index b98b8a1f4cc27..abb711c6f09d0 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/create_conversation.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/create_conversation.ts @@ -34,10 +34,10 @@ export const createConversation = async ({ logger, }: CreateConversationParams): Promise => { const createdAt = new Date().toISOString(); - const body = transformToCreateScheme(createdAt, spaceId, user, conversation); + const document = transformToCreateScheme(createdAt, spaceId, user, conversation); try { const response = await esClient.create({ - body, + document, id: conversation?.id || uuidv4(), index: conversationIndex, refresh: 'wait_for', diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/delete_conversation.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/delete_conversation.ts index 38914ce2e8db4..0b9171804f972 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/delete_conversation.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/delete_conversation.ts @@ -21,11 +21,9 @@ export const deleteConversation = async ({ }: DeleteConversationParams): Promise => { try { const response = await esClient.deleteByQuery({ - body: { - query: { - ids: { - values: [id], - }, + query: { + ids: { + values: [id], }, }, conflicts: 'proceed', diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.test.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.test.ts index 43290c8a00293..41e33acf76b13 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.test.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.test.ts @@ -8,7 +8,7 @@ import type { Logger } from '@kbn/core/server'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { getConversation } from './get_conversation'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EsConversationSchema } from './types'; import { authenticatedUser } from '../../__mocks__/user'; import { loggingSystemMock } from '@kbn/core-logging-server-mocks'; diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.ts index 94b8531632178..2c30aacd41af9 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/get_conversation.ts @@ -47,24 +47,22 @@ export const getConversation = async ({ : []; try { const response = await esClient.search({ - body: { - query: { - bool: { - must: [ - { - bool: { - should: [ - { - term: { - _id: id, - }, + query: { + bool: { + must: [ + { + bool: { + should: [ + { + term: { + _id: id, }, - ], - }, + }, + ], }, - ...filterByUser, - ], - }, + }, + ...filterByUser, + ], }, }, _source: true, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/transforms.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/transforms.ts index c11d872e9d3ec..fc35ac24d56fe 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/transforms.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/conversations/transforms.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { ConversationResponse, Replacements, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/defend_insights/index.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/defend_insights/index.ts index b5cbbd6cd18a2..064d918ec9a16 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/defend_insights/index.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/defend_insights/index.ts @@ -80,10 +80,10 @@ export class DefendInsightsDataClient extends AIAssistantDataClient { const id = defendInsightCreate?.id || uuidv4(); const createdAt = new Date().toISOString(); - const body = transformToCreateScheme(createdAt, this.spaceId, user, defendInsightCreate); + const document = transformToCreateScheme(createdAt, this.spaceId, user, defendInsightCreate); try { const response = await esClient.create({ - body, + document, id, index, refresh: 'wait_for', diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.test.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.test.ts index 8108376c843b4..22bd880226488 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.test.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.test.ts @@ -7,7 +7,7 @@ import type { Logger } from '@kbn/core/server'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { loggingSystemMock } from '@kbn/core-logging-server-mocks'; import { findDocuments } from './find'; import { EsConversationSchema } from './conversations/types'; diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.ts index 9f37e45250a9c..e5df767793375 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/find.ts @@ -13,7 +13,7 @@ import { } from '@elastic/elasticsearch/lib/api/types'; import { ElasticsearchClient, Logger } from '@kbn/core/server'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { EsQueryConfig, Query, buildEsQuery } from '@kbn/es-query'; interface FindOptions { @@ -69,11 +69,9 @@ export const findDocuments = async ({ try { if (mSearch == null) { const response = await esClient.search({ - body: { - query, - track_total_hits: true, - sort, - }, + query, + track_total_hits: true, + sort, _source: true, from: (page - 1) * perPage, ignore_unavailable: true, @@ -94,7 +92,7 @@ export const findDocuments = async ({ }; } const mSearchQueryBody = { - body: [ + searches: [ { index }, { query, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/index.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/index.ts index f17ffac7d42ac..fc02b05af3360 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/index.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/index.ts @@ -9,7 +9,7 @@ import { AuditLogger, AuthenticatedUser, ElasticsearchClient, Logger } from '@kb import { DEFAULT_NAMESPACE_STRING } from '@kbn/core-saved-objects-utils-server'; import { ESSearchRequest, ESSearchResponse } from '@kbn/es-types'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { IIndexPatternString } from '../types'; import { getIndexTemplateAndPattern } from '../lib/data_stream/helpers'; import { DocumentsDataWriter } from '../lib/data_stream/documents_data_writer'; diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.test.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.test.ts index df6533d5d8df2..cb3f2f7d947c0 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.test.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.test.ts @@ -66,7 +66,7 @@ describe('createKnowledgeBaseEntry', () => { telemetry, }); expect(esClient.create).toHaveBeenCalledWith({ - body: { + document: { '@timestamp': '2024-01-28T04:20:02.394Z', created_at: '2024-01-28T04:20:02.394Z', created_by: 'my_profile_uid', @@ -118,7 +118,7 @@ describe('createKnowledgeBaseEntry', () => { telemetry, }); expect(esClient.create).toHaveBeenCalledWith({ - body: { + document: { '@timestamp': '2024-01-28T04:20:02.394Z', created_at: '2024-01-28T04:20:02.394Z', created_by: 'my_profile_uid', diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.ts index cda1781c3a1e9..1ff40f37950da 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/create_knowledge_base_entry.ts @@ -51,7 +51,7 @@ export const createKnowledgeBaseEntry = async ({ telemetry, }: CreateKnowledgeBaseEntryParams): Promise => { const createdAt = new Date().toISOString(); - const body = transformToCreateSchema({ + const document = transformToCreateSchema({ createdAt, spaceId, user, @@ -59,14 +59,14 @@ export const createKnowledgeBaseEntry = async ({ global, }); const telemetryPayload = { - entryType: body.type, - required: body.required ?? false, - sharing: body.users.length ? 'private' : 'global', - ...(body.type === 'document' ? { source: body.source } : {}), + entryType: document.type, + required: document.required ?? false, + sharing: document.users.length ? 'private' : 'global', + ...(document.type === 'document' ? { source: document.source } : {}), }; try { const response = await esClient.create({ - body, + document, id: uuidv4(), index: knowledgeBaseIndex, refresh: 'wait_for', diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/index.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/index.ts index 561467f2256ea..b67937d570236 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/index.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/index.ts @@ -205,7 +205,7 @@ export class AIAssistantKnowledgeBaseDataClient extends AIAssistantDataClient { // For standardized way of checking deployment status see: https://github.com/elastic/elasticsearch/issues/106986 const isReadyESS = (stats: MlTrainedModelStats) => stats.deployment_stats?.state === 'started' && - stats.deployment_stats?.allocation_status.state === 'fully_allocated'; + stats.deployment_stats?.allocation_status?.state === 'fully_allocated'; const isReadyServerless = (stats: MlTrainedModelStats) => (stats.deployment_stats?.nodes as unknown as MlTrainedModelDeploymentNodesStats[])?.some( diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/transforms.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/transforms.ts index 16ef4ffb0595e..6c3c8bb5658bb 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/transforms.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/knowledge_base/transforms.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { DocumentEntry, DocumentEntryType, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/prompts/helpers.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/prompts/helpers.ts index eb71270127b2a..804644218cc03 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/prompts/helpers.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_data_clients/prompts/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { PromptCreateProps, PromptResponse, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_service/index.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_service/index.ts index 9aef0e6c8db58..f1e431b63adcd 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_service/index.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/ai_assistant_service/index.ts @@ -703,9 +703,7 @@ export class AIAssistantService { const existingAnonymizationFields = await ( await dataClient?.getReader() ).search({ - body: { - size: 1, - }, + size: 1, allow_no_indices: true, }); if (existingAnonymizationFields.hits.total.value === 0) { diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/create_attack_discovery/create_attack_discovery.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/create_attack_discovery/create_attack_discovery.ts index fc511dc559d30..2732df6f0899f 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/create_attack_discovery/create_attack_discovery.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/create_attack_discovery/create_attack_discovery.ts @@ -30,11 +30,11 @@ export const createAttackDiscovery = async ({ logger, }: CreateAttackDiscoveryParams): Promise => { const createdAt = new Date().toISOString(); - const body = transformToCreateScheme(createdAt, spaceId, user, attackDiscoveryCreate); + const document = transformToCreateScheme(createdAt, spaceId, user, attackDiscoveryCreate); const id = attackDiscoveryCreate?.id || uuidv4(); try { const response = await esClient.create({ - body, + document, id, index: attackDiscoveryIndex, refresh: 'wait_for', diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/transforms/transforms.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/transforms/transforms.ts index 765d40f7a3226..a7c58846a51e6 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/transforms/transforms.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/lib/attack_discovery/persistence/transforms/transforms.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { AttackDiscoveryResponse } from '@kbn/elastic-assistant-common'; import { EsAttackDiscoverySchema } from '../types'; diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/lib/data_stream/documents_data_writer.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/lib/data_stream/documents_data_writer.ts index f065d0a2f8424..af3122398e77a 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/lib/data_stream/documents_data_writer.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/lib/data_stream/documents_data_writer.ts @@ -163,24 +163,22 @@ export class DocumentsDataWriter implements DocumentsDataWriter { const updatedAt = new Date().toISOString(); const responseToUpdate = await this.options.esClient.search({ - body: { - query: { - bool: { - must: [ - { - bool: { - should: [ - { - ids: { - values: documentsToUpdate?.map((c) => c.id), - }, + query: { + bool: { + must: [ + { + bool: { + should: [ + { + ids: { + values: documentsToUpdate?.map((c) => c.id), }, - ], - }, + }, + ], }, - ], - ...(authenticatedUser ? this.getFilterByUser(authenticatedUser) : {}), - }, + }, + ], + ...(authenticatedUser ? this.getFilterByUser(authenticatedUser) : {}), }, }, _source: false, @@ -211,24 +209,22 @@ export class DocumentsDataWriter implements DocumentsDataWriter { authenticatedUser?: AuthenticatedUser ) => { const responseToDelete = await this.options.esClient.search({ - body: { - query: { - bool: { - must: [ - { - bool: { - should: [ - { - ids: { - values: documentsToDelete, - }, + query: { + bool: { + must: [ + { + bool: { + should: [ + { + ids: { + values: documentsToDelete, }, - ], - }, + }, + ], }, - ], - ...(authenticatedUser ? this.getFilterByUser(authenticatedUser) : {}), - }, + }, + ], + ...(authenticatedUser ? this.getFilterByUser(authenticatedUser) : {}), }, }, _source: false, diff --git a/x-pack/solutions/security/plugins/elastic_assistant/server/routes/knowledge_base/entries/find_route.ts b/x-pack/solutions/security/plugins/elastic_assistant/server/routes/knowledge_base/entries/find_route.ts index 6823c8d346b87..78ba8964a9895 100644 --- a/x-pack/solutions/security/plugins/elastic_assistant/server/routes/knowledge_base/entries/find_route.ts +++ b/x-pack/solutions/security/plugins/elastic_assistant/server/routes/knowledge_base/entries/find_route.ts @@ -18,7 +18,7 @@ import { FindKnowledgeBaseEntriesResponse, } from '@kbn/elastic-assistant-common'; import { buildRouteValidationWithZod } from '@kbn/elastic-assistant-common/impl/schemas/common'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticAssistantPluginRouter } from '../../../types'; import { buildResponse } from '../../utils'; diff --git a/x-pack/solutions/security/plugins/lists/server/schemas/common/get_shard.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/common/get_shard.mock.ts index e7a887d6ca354..43511a748ba1a 100644 --- a/x-pack/solutions/security/plugins/lists/server/schemas/common/get_shard.mock.ts +++ b/x-pack/solutions/security/plugins/lists/server/schemas/common/get_shard.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export const getShardMock = (): estypes.ShardStatistics => ({ failed: 0, diff --git a/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts index b8369c8ed06a1..bb8a5a4685b5a 100644 --- a/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts +++ b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DATE_NOW, diff --git a/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts index 00ce8b58d7e0a..b7a9fcda166ce 100644 --- a/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts +++ b/x-pack/solutions/security/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DATE_NOW, diff --git a/x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.ts b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.ts index 8e453a30fc766..a56cf8893eb88 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/exception_lists/build_exception_filter.ts @@ -26,7 +26,7 @@ import { entriesNested, } from '@kbn/securitysolution-io-ts-list-types'; import type { Filter } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { partition } from 'lodash'; import { hasLargeValueList } from '@kbn/securitysolution-list-utils'; import { diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.test.ts index 91e67f8571c0a..a0e7a6695a0c2 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.test.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.test.ts @@ -45,22 +45,20 @@ describe('delete_list_item_by_value', () => { const options = getDeleteListItemByValueOptionsMock(); await deleteListItemByValue(options); const deleteByQuery = { - body: { - query: { - bool: { - filter: [ - { term: { list_id: 'some-list-id' } }, - { - bool: { - minimum_should_match: 1, - should: [{ term: { ip: { _name: '0.0', value: '127.0.0.1' } } }], - }, + index: '.items', + query: { + bool: { + filter: [ + { term: { list_id: 'some-list-id' } }, + { + bool: { + minimum_should_match: 1, + should: [{ term: { ip: { _name: '0.0', value: '127.0.0.1' } } }], }, - ], - }, + }, + ], }, }, - index: '.items', refresh: false, }; expect(options.esClient.deleteByQuery).toBeCalledWith(deleteByQuery); diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.ts b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.ts index 0efe99436dea5..00ff9d79d5f1a 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/delete_list_item_by_value.ts @@ -43,14 +43,12 @@ export const deleteListItemByValue = async ({ value: values, }); await esClient.deleteByQuery({ - body: { - query: { - bool: { - filter, - }, + index: listItemIndex, + query: { + bool: { + filter, }, }, - index: listItemIndex, refresh, }); return listItems; diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.mock.ts index 9ffe66a236ff7..70b3f164e9b3f 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.mock.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { LIST_ID, LIST_INDEX, LIST_ITEM_INDEX } from '../../../common/constants.mock'; diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.ts index dbd24ff36d2af..942e5c63f69ad 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/find_all_list_items.ts @@ -50,22 +50,18 @@ export const findAllListItems = async ({ const query = getQueryFilterWithListId({ filter, listId }); const sort = getSortWithTieBreaker({ sortField, sortOrder }); const { count } = await esClient.count({ - body: { - query, - }, ignore_unavailable: true, index: listItemIndex, + query, }); let response = await esClient.search({ - body: { - query, - sort, - }, ignore_unavailable: true, index: listItemIndex, + query, seq_no_primary_term: true, size: 10000, + sort, }); if (count > 100000) { @@ -80,15 +76,13 @@ export const findAllListItems = async ({ } response = await esClient.search({ - body: { - query, - search_after: response.hits.hits[response.hits.hits.length - 1].sort, - sort, - }, ignore_unavailable: true, index: listItemIndex, + query, + search_after: response.hits.hits[response.hits.hits.length - 1].sort, seq_no_primary_term: true, size: 10000, + sort, }); } return { diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.mock.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.mock.ts index 7895aa4fd790b..e71398ada2e39 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.mock.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { LIST_ID, LIST_INDEX, LIST_ITEM_INDEX } from '../../../common/constants.mock'; diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.ts index ba23cb6aad76c..bec144d752936 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/find_list_item.ts @@ -86,12 +86,10 @@ export const findListItem = async ({ }); const respose = await esClient.search({ - body: { - query, - runtime_mappings: runtimeMappings, - }, ignore_unavailable: true, index: listItemIndex, + query, + runtime_mappings: runtimeMappings, size: 0, track_total_hits: true, }); @@ -101,15 +99,13 @@ export const findListItem = async ({ // is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have // to explicitly define the type . const response = await esClient.search({ - body: { - query, - search_after: scroll.searchAfter, - sort: getSortWithTieBreaker({ sortField, sortOrder }), - }, ignore_unavailable: true, index: listItemIndex, + query, + search_after: scroll.searchAfter, seq_no_primary_term: true, size: perPage, + sort: getSortWithTieBreaker({ sortField, sortOrder }), }); return { cursor: encodeCursor({ diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.ts index f08900522b722..cf468254d3e22 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item.ts @@ -27,15 +27,13 @@ export const getListItem = async ({ // is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have // to explicitly define the type . const listItemES = await esClient.search({ - body: { - query: { - term: { - _id: id, - }, - }, - }, ignore_unavailable: true, index: listItemIndex, + query: { + term: { + _id: id, + }, + }, seq_no_primary_term: true, }); diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.ts b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.ts index 867d721d8440c..5095c350a791a 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/get_list_item_by_values.ts @@ -34,15 +34,13 @@ export const getListItemByValues = async ({ // using PIT, don't want it to get lost // https://github.com/elastic/kibana/issues/103944 const response = await esClient.search({ - body: { - query: { - bool: { - filter: getQueryFilterFromTypeValue({ listId, type, value }), - }, - }, - }, ignore_unavailable: true, index: listItemIndex, + query: { + bool: { + filter: getQueryFilterFromTypeValue({ listId, type, value }), + }, + }, size: 10000, // TODO: This has a limit on the number which is 10,000 the default of Elastic but we might want to provide a way to increase that number }); return transformElasticToListItem({ diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.ts b/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.ts index 365c5a57c724b..62706690294dd 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/search_list_item_by_values.ts @@ -34,15 +34,13 @@ export const searchListItemByValues = async ({ // using PIT, don't want it to get lost // https://github.com/elastic/kibana/issues/103944 const response = await esClient.search({ - body: { - query: { - bool: { - filter: getQueryFilterFromTypeValue({ listId, type, value }), - }, - }, - }, ignore_unavailable: true, index: listItemIndex, + query: { + bool: { + filter: getQueryFilterFromTypeValue({ listId, type, value }), + }, + }, size: 10000, // TODO: This has a limit on the number which is 10,000 the default of Elastic but we might want to provide a way to increase that number }); return transformElasticNamedSearchToListItem({ diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.test.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.test.ts index 0c12d38fb9746..0fa133bbeaf70 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.test.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.test.ts @@ -189,14 +189,12 @@ describe('write_list_items_to_stream', () => { options.searchAfter = ['string 1', 'string 2']; await getResponse(options); const expected = { - body: { - query: { term: { list_id: LIST_ID } }, - search_after: ['string 1', 'string 2'], - sort: [{ tie_breaker_id: 'asc' }], - }, ignore_unavailable: true, index: LIST_ITEM_INDEX, + query: { term: { list_id: LIST_ID } }, + search_after: ['string 1', 'string 2'], size: 100, + sort: [{ tie_breaker_id: 'asc' }], }; expect(options.esClient.search).toBeCalledWith(expected); }); @@ -207,14 +205,12 @@ describe('write_list_items_to_stream', () => { options.size = 33; await getResponse(options); const expected = { - body: { - query: { term: { list_id: LIST_ID } }, - search_after: ['string 1', 'string 2'], - sort: [{ tie_breaker_id: 'asc' }], - }, ignore_unavailable: true, index: LIST_ITEM_INDEX, + query: { term: { list_id: LIST_ID } }, + search_after: ['string 1', 'string 2'], size: 33, + sort: [{ tie_breaker_id: 'asc' }], }; expect(options.esClient.search).toBeCalledWith(expected); }); diff --git a/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.ts b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.ts index 8c375a3c178e2..75c25f5ef79b2 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/items/write_list_items_to_stream.ts @@ -7,7 +7,7 @@ import { PassThrough } from 'stream'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient } from '@kbn/core/server'; import { ErrorWithStatusCode } from '../../error_with_status_code'; @@ -117,18 +117,16 @@ export const getResponse = async ({ size = SIZE, }: GetResponseOptions): Promise> => { return (await esClient.search({ - body: { - query: { - term: { - list_id: listId, - }, - }, - search_after: searchAfter, - sort: [{ tie_breaker_id: 'asc' }], - }, ignore_unavailable: true, index: listItemIndex, + query: { + term: { + list_id: listId, + }, + }, + search_after: searchAfter, size, + sort: [{ tie_breaker_id: 'asc' }], })) as unknown as estypes.SearchResponse; }; diff --git a/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.test.ts index 86c0155c43ec4..1de16b82efd13 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.test.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.test.ts @@ -62,7 +62,7 @@ describe('create_list', () => { await createList(options); const body = getIndexESListMock(); const expected = { - body, + document: body, id: LIST_ID, index: LIST_INDEX, refresh: 'wait_for', diff --git a/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.ts index cd3497b6e891a..8ba231fbe9590 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/lists/create_list.ts @@ -75,7 +75,7 @@ export const createList = async ({ }; const response = await esClient.create({ - body, + document: body, id: id ?? uuidv4(), index: listIndex, refresh: 'wait_for', diff --git a/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.test.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.test.ts index dd2a8639e9278..e1501345a5bda 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.test.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.test.ts @@ -52,9 +52,9 @@ describe('delete_list', () => { options.esClient.deleteByQuery = jest.fn().mockResolvedValue({ deleted: 1 }); await deleteList(options); const deleteByQuery = { - body: { query: { term: { list_id: LIST_ID } } }, conflicts: 'proceed', index: LIST_ITEM_INDEX, + query: { term: { list_id: LIST_ID } }, refresh: false, }; expect(options.esClient.deleteByQuery).toHaveBeenNthCalledWith(1, deleteByQuery); @@ -67,15 +67,13 @@ describe('delete_list', () => { options.esClient.deleteByQuery = jest.fn().mockResolvedValue({ deleted: 1 }); await deleteList(options); const deleteByQuery = { - body: { - query: { - ids: { - values: [LIST_ID], - }, - }, - }, conflicts: 'proceed', index: LIST_INDEX, + query: { + ids: { + values: [LIST_ID], + }, + }, refresh: false, }; expect(options.esClient.deleteByQuery).toHaveBeenCalledWith(deleteByQuery); diff --git a/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.ts index c6b452675b7c3..512b3c21ccbcb 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/lists/delete_list.ts @@ -30,28 +30,24 @@ export const deleteList = async ({ return null; } else { await esClient.deleteByQuery({ - body: { - query: { - term: { - list_id: id, - }, - }, - }, conflicts: 'proceed', index: listItemIndex, + query: { + term: { + list_id: id, + }, + }, refresh: false, }); const response = await esClient.deleteByQuery({ - body: { - query: { - ids: { - values: [id], - }, - }, - }, conflicts: 'proceed', index: listIndex, + query: { + ids: { + values: [id], + }, + }, refresh: false, }); diff --git a/x-pack/solutions/security/plugins/lists/server/services/lists/find_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/find_list.ts index 09a13b745d89e..58b1869859bec 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/lists/find_list.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/lists/find_list.ts @@ -68,11 +68,9 @@ export const findList = async ({ }); const totalCount = await esClient.count({ - body: { - query, - }, ignore_unavailable: true, index: listIndex, + query, }); if (scroll.validSearchAfterFound) { @@ -80,15 +78,13 @@ export const findList = async ({ // is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have // to explicitly define the type . const response = await esClient.search({ - body: { - query, - search_after: scroll.searchAfter, - sort: getSortWithTieBreaker({ sortField, sortOrder }), - }, ignore_unavailable: true, index: listIndex, + query, + search_after: scroll.searchAfter, seq_no_primary_term: true, size: perPage, + sort: getSortWithTieBreaker({ sortField, sortOrder }), }); return { cursor: encodeCursor({ diff --git a/x-pack/solutions/security/plugins/lists/server/services/lists/get_list.ts b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list.ts index 32c9efaab8c2a..ea199f65287ea 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/lists/get_list.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/lists/get_list.ts @@ -26,15 +26,13 @@ export const getList = async ({ // is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have // to explicitly define the type . const response = await esClient.search({ - body: { - query: { - term: { - _id: id, - }, - }, - }, ignore_unavailable: true, index: listIndex, + query: { + term: { + _id: id, + }, + }, seq_no_primary_term: true, }); const list = transformElasticToList({ response }); diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts index 8d0d2501475e6..db667951381b0 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isEmpty, isObject } from 'lodash/fp'; import type { Type } from '@kbn/securitysolution-io-ts-list-types'; diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_scroll.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_scroll.ts index 04ab24e334988..9df370485a99f 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_scroll.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_scroll.ts @@ -47,16 +47,14 @@ export const getSearchAfterScroll = async ({ let newSearchAfter = searchAfter; for (let i = 0; i < hops; ++i) { const response = await esClient.search>({ - body: { - _source: getSourceWithTieBreaker({ sortField }), - query, - runtime_mappings: runtimeMappings, - search_after: newSearchAfter, - sort: getSortWithTieBreaker({ sortField, sortOrder }), - }, + _source: getSourceWithTieBreaker({ sortField }), ignore_unavailable: true, index, + query, + runtime_mappings: runtimeMappings, + search_after: newSearchAfter, size: hopSize, + sort: getSortWithTieBreaker({ sortField, sortOrder }), }); if (response.hits.hits.length > 0) { newSearchAfter = getSearchAfterWithTieBreaker({ response, sortField }); diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts index 37794228bd693..7db46ce1a464c 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SortFieldOrUndefined } from '@kbn/securitysolution-io-ts-list-types'; export type TieBreaker = T & { diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts index ef1e490d28d4b..dbcec20d3d8a8 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SortFieldOrUndefined, SortOrderOrUndefined } from '@kbn/securitysolution-io-ts-list-types'; export const getSortWithTieBreaker = ({ diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts index abdffd19eca76..57bbe39011084 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { SearchListItemArraySchema, Type } from '@kbn/securitysolution-io-ts-list-types'; import { SearchEsListItemSchema } from '../../schemas/elastic_response'; diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list.ts index 8247f5281d6ee..e0dbcd50980df 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ListArraySchema } from '@kbn/securitysolution-io-ts-list-types'; import { encodeHitVersion } from '@kbn/securitysolution-es-utils'; diff --git a/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts index 060f4fa279681..d573f4652869d 100644 --- a/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts +++ b/x-pack/solutions/security/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ListItemArraySchema, Type } from '@kbn/securitysolution-io-ts-list-types'; import { encodeHitVersion } from '@kbn/securitysolution-es-utils'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/base_data_generator.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/base_data_generator.ts index 2e35fd290681d..3949a4e69ca98 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/base_data_generator.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/base_data_generator.ts @@ -7,7 +7,7 @@ import seedrandom from 'seedrandom'; import { v4 as uuidv4 } from 'uuid'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; const OS_FAMILY = ['windows', 'macos', 'linux']; /** Array of 14 day offsets */ diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/endpoint_action_generator.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/endpoint_action_generator.ts index e221bad5fcb28..5a27aa9283ffb 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/endpoint_action_generator.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/endpoint_action_generator.ts @@ -7,7 +7,7 @@ import type { DeepPartial } from 'utility-types'; import { merge } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isProcessesAction } from '../service/response_actions/type_guards'; import { ENDPOINT_ACTION_RESPONSES_DS, ENDPOINT_ACTIONS_DS } from '../constants'; import { BaseDataGenerator } from './base_data_generator'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_action_generator.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_action_generator.ts index 44da774a415d9..be6af24a8da80 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_action_generator.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_action_generator.ts @@ -7,7 +7,7 @@ import type { DeepPartial } from 'utility-types'; import { merge } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { AGENT_ACTIONS_INDEX, AGENT_ACTIONS_RESULTS_INDEX } from '@kbn/fleet-plugin/common'; import { BaseDataGenerator } from './base_data_generator'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts index 85d5053850237..d81af73b7c17b 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { DeepPartial } from 'utility-types'; import { merge } from 'lodash'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_fleet_actions.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_fleet_actions.ts index 5eb2cebcc3f8e..73631059869b5 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_fleet_actions.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_fleet_actions.ts @@ -5,8 +5,7 @@ * 2.0. */ -import type { Client } from '@elastic/elasticsearch'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { Client, estypes } from '@elastic/elasticsearch'; import { AGENT_ACTIONS_INDEX, AGENT_ACTIONS_RESULTS_INDEX } from '@kbn/fleet-plugin/common'; import type { BulkRequest } from '@elastic/elasticsearch/lib/api/types'; import type { ResponseActionsApiCommandNames } from '../service/response_actions/constants'; @@ -340,13 +339,11 @@ export const deleteIndexedEndpointAndFleetActions = async ( .deleteByQuery({ index: `${indexedData.actionsIndex}-*`, wait_for_completion: true, - body: { - query: { - bool: { - filter: [ - { terms: { action_id: indexedData.actions.map((action) => action.action_id) } }, - ], - }, + query: { + bool: { + filter: [ + { terms: { action_id: indexedData.actions.map((action) => action.action_id) } }, + ], }, }, }) @@ -355,13 +352,11 @@ export const deleteIndexedEndpointAndFleetActions = async ( .deleteByQuery({ index: `${indexedData.endpointActionsIndex}-*`, wait_for_completion: true, - body: { - query: { - bool: { - filter: [ - { terms: { action_id: indexedData.actions.map((action) => action.action_id) } }, - ], - }, + query: { + bool: { + filter: [ + { terms: { action_id: indexedData.actions.map((action) => action.action_id) } }, + ], }, }, }) @@ -375,17 +370,15 @@ export const deleteIndexedEndpointAndFleetActions = async ( .deleteByQuery({ index: `${indexedData.responsesIndex}-*`, wait_for_completion: true, - body: { - query: { - bool: { - filter: [ - { - terms: { - action_id: indexedData.actionResponses.map((action) => action.action_id), - }, + query: { + bool: { + filter: [ + { + terms: { + action_id: indexedData.actionResponses.map((action) => action.action_id), }, - ], - }, + }, + ], }, }, }) @@ -394,17 +387,15 @@ export const deleteIndexedEndpointAndFleetActions = async ( .deleteByQuery({ index: `${indexedData.endpointActionResponsesIndex}-*`, wait_for_completion: true, - body: { - query: { - bool: { - filter: [ - { - terms: { - action_id: indexedData.actionResponses.map((action) => action.action_id), - }, + query: { + bool: { + filter: [ + { + terms: { + action_id: indexedData.actionResponses.map((action) => action.action_id), }, - ], - }, + }, + ], }, }, }) diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts index 8f1f9c7e21c08..2f221579eb497 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts @@ -10,9 +10,8 @@ import { cloneDeep } from 'lodash'; import type { AxiosResponse } from 'axios'; import { v4 as uuidv4 } from 'uuid'; import type { KbnClient } from '@kbn/test'; -import type { DeleteByQueryResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { BulkRequest, DeleteByQueryResponse } from '@elastic/elasticsearch/lib/api/types'; import type { CreatePackagePolicyResponse, GetInfoResponse } from '@kbn/fleet-plugin/common'; -import type { BulkRequest } from '@elastic/elasticsearch/lib/api/types'; import { EndpointError } from '../errors'; import { usageTracker } from './usage_tracker'; import { EndpointDocGenerator } from '../generate_data'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts index 46f7034537134..9367eef195135 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts @@ -7,12 +7,12 @@ import type { Client } from '@elastic/elasticsearch'; import type { + BulkRequest, DeleteByQueryResponse, IndexRequest, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { FleetServerAgent } from '@kbn/fleet-plugin/common'; import { AGENTS_INDEX } from '@kbn/fleet-plugin/common'; -import type { BulkRequest } from '@elastic/elasticsearch/lib/api/types'; import type { DeepPartial } from 'utility-types'; import type { ToolingLog } from '@kbn/tooling-log'; import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common'; @@ -131,19 +131,17 @@ export const deleteIndexedFleetAgents = async ( .deleteByQuery({ index: `${indexedData.fleetAgentsIndex}-*`, wait_for_completion: true, - body: { - query: { - bool: { - filter: [ - { - terms: { - 'local_metadata.elastic.agent.id': indexedData.agents.map( - (agent) => agent.local_metadata.elastic.agent.id - ), - }, + query: { + bool: { + filter: [ + { + terms: { + 'local_metadata.elastic.agent.id': indexedData.agents.map( + (agent) => agent.local_metadata.elastic.agent.id + ), }, - ], - }, + }, + ], }, }, }) diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/transforms.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/transforms.ts index 7d402108b9724..e26d59e4e92b4 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/transforms.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/transforms.ts @@ -6,7 +6,7 @@ */ import type { Client } from '@elastic/elasticsearch'; -import type { TransformGetTransformStatsTransformStats } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { TransformGetTransformStatsTransformStats } from '@elastic/elasticsearch/lib/api/types'; import { isEndpointPackageV2 } from './package_v2'; import { usageTracker } from '../data_loaders/usage_tracker'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/response.ts b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/response.ts index 2ce5d3ff86fcd..6c61b58a0642e 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/response.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/response.ts @@ -6,7 +6,7 @@ */ import type { IKibanaSearchResponse } from '@kbn/search-types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { LogsEndpointActionResponse } from '../../../endpoint/types'; import type { SortOrder, Inspect, Maybe, RequestBasicOptions } from './types'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/types.ts b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/types.ts index 8508011bd7a7b..4b3967c02412e 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/endpoint/response_actions/types.ts @@ -6,7 +6,7 @@ */ import type { IEsSearchRequest } from '@kbn/search-types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { LogsOsqueryAction } from '@kbn/osquery-plugin/common/types/osquery_action'; import type { LogsEndpointActionWithHosts } from '../../../endpoint/types'; import type { ResponseActionsQueries } from '.'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/cti/index.ts b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/cti/index.ts index 290cd6e57eb92..089093cf0a863 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/cti/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/cti/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IEsSearchResponse } from '@kbn/search-types'; import { EVENT_ENRICHMENT_INDICATOR_FIELD_MAP } from '../../../cti/constants'; import type { Inspect, Maybe } from '../../common'; diff --git a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts index 4a03292eff47d..a74135ce985a9 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IEsSearchResponse } from '@kbn/search-types'; import type { Inspect, Maybe } from '../../../common'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts b/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts index 5fa33c8becfca..169b6fe58a493 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts @@ -6,7 +6,7 @@ */ import { useEffect, useMemo } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DEFAULT_ANOMALY_SCORE } from '../../../../../common/constants'; import { anomaliesTableData } from '../api/anomalies_table_data'; import type { InfluencerInput, Anomalies, CriteriaFields } from '../types'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts b/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts index 3b1ea298e7ba9..72fc6e2d3b355 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/ml/api/anomalies_table_data.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Anomalies, InfluencerInput, CriteriaFields } from '../types'; import { KibanaServices } from '../../../lib/kibana'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/containers/source/mock.ts b/x-pack/solutions/security/plugins/security_solution/public/common/containers/source/mock.ts index 3b493cf2566b9..db107ac619cf7 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/containers/source/mock.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/containers/source/mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MappingRuntimeFieldType } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFieldType } from '@elastic/elasticsearch/lib/api/types'; import { flatten } from 'lodash'; import type { BrowserFields } from '../../../../common/search_strategy/index_fields'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/hooks/eql/api.ts b/x-pack/solutions/security/plugins/security_solution/public/common/hooks/eql/api.ts index b26f935612755..d8c8c4dab5abc 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/hooks/eql/api.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/hooks/eql/api.ts @@ -9,7 +9,7 @@ import { firstValueFrom } from 'rxjs'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { EqlSearchStrategyRequest, EqlSearchStrategyResponse } from '@kbn/data-plugin/common'; import { EQL_SEARCH_STRATEGY } from '@kbn/data-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EqlOptions } from '../../../../common/search_strategy'; import { @@ -68,7 +68,9 @@ export const validateEql = async ({ { params: { index: dataViewTitle, - body: { query, runtime_mappings: runtimeMappings, size: 0 }, + query, + runtime_mappings: runtimeMappings, + size: 0, // Prevent passing empty string values timestamp_field: eqlOptions?.timestampField ? eqlOptions.timestampField : undefined, tiebreaker_field: eqlOptions?.tiebreakerField ? eqlOptions.tiebreakerField : undefined, diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_exceptions/logic/use_close_alerts.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_exceptions/logic/use_close_alerts.tsx index 0566788d700ae..257f6b776bc08 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_exceptions/logic/use_close_alerts.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_exceptions/logic/use_close_alerts.tsx @@ -6,7 +6,7 @@ */ import { useEffect, useRef, useState } from 'react'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; import { buildAlertStatusesFilter, diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_by_rule_panel/alerts_by_rule.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_by_rule_panel/alerts_by_rule.tsx index 4cda599776fa9..9af2884b672ed 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_by_rule_panel/alerts_by_rule.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_by_rule_panel/alerts_by_rule.tsx @@ -9,7 +9,7 @@ import type { EuiBasicTableColumn } from '@elastic/eui'; import { EuiInMemoryTable, EuiSpacer, EuiText } from '@elastic/eui'; import React from 'react'; import styled from 'styled-components'; -import type { SortOrder } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SortOrder } from '@elastic/elasticsearch/lib/api/types'; import { ALERT_RULE_NAME } from '@kbn/rule-data-utils'; import { TableId } from '@kbn/securitysolution-data-table'; import type { AlertsByRuleData } from './types'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_treemap_panel/alerts_treemap/query/index.ts b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_treemap_panel/alerts_treemap/query/index.ts index cd73b9a5af434..1f291ff7fb026 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_treemap_panel/alerts_treemap/query/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_treemap_panel/alerts_treemap/query/index.ts @@ -6,7 +6,7 @@ */ import { isEmpty } from 'lodash/fp'; -import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/types'; /** The maximum number of items to render */ export const DEFAULT_STACK_BY_FIELD0_SIZE = 1000; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_table/actions.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_table/actions.tsx index 822adecbe8c4d..e98aa33528df6 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_table/actions.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_table/actions.tsx @@ -11,7 +11,7 @@ import { isEmpty } from 'lodash/fp'; import moment from 'moment'; import dateMath from '@kbn/datemath'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Filter } from '@kbn/es-query'; import { FilterStateStore } from '@kbn/es-query'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts b/x-pack/solutions/security/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts index 0b198793a31ff..df237fa035326 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { getCasesFromAlertsUrl } from '@kbn/cases-plugin/common'; import type { ResponseActionAgentType } from '../../../../../common/endpoint/service/response_actions/constants'; import type { ResponseActionApiResponse, HostInfo } from '../../../../../common/endpoint/types'; diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_fetch_prevalence.ts b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_fetch_prevalence.ts index afe08d1339827..3b27ff0e00d36 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_fetch_prevalence.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/hooks/use_fetch_prevalence.ts @@ -163,50 +163,48 @@ const buildAggregationSearchRequest = ( ): IEsSearchRequest => ({ params: { index: selectedPatterns, - body: { - query, - aggs: { - // with this aggregation, we can in a single call retrieve all the values for each field/value pairs - [FIELD_NAMES_AGG_KEY]: { - filters: { - filters: highlightedFieldsFilters, - }, - aggs: { - // this sub aggregation allows us to retrieve all the hosts which have the field/value pair - [HOST_NAME_AGG_KEY]: { - cardinality: { - field: 'host.name', - }, + query, + aggs: { + // with this aggregation, we can in a single call retrieve all the values for each field/value pairs + [FIELD_NAMES_AGG_KEY]: { + filters: { + filters: highlightedFieldsFilters, + }, + aggs: { + // this sub aggregation allows us to retrieve all the hosts which have the field/value pair + [HOST_NAME_AGG_KEY]: { + cardinality: { + field: 'host.name', }, - // this sub aggregation allows us to retrieve all the users which have the field/value pair - [USER_NAME_AGG_KEY]: { - cardinality: { - field: 'user.name', - }, + }, + // this sub aggregation allows us to retrieve all the users which have the field/value pair + [USER_NAME_AGG_KEY]: { + cardinality: { + field: 'user.name', }, - // we use this sub aggregation to differentiate between alerts (event.kind === 'signal') and documents (event.kind !== 'signal') - [EVENT_KIND_AGG_KEY]: { - terms: { - field: 'event.kind', - size: 10, // there should be only 8 different value for the event.kind field - }, + }, + // we use this sub aggregation to differentiate between alerts (event.kind === 'signal') and documents (event.kind !== 'signal') + [EVENT_KIND_AGG_KEY]: { + terms: { + field: 'event.kind', + size: 10, // there should be only 8 different value for the event.kind field }, }, }, - // retrieve all the unique hosts in the environment - [HOSTS_AGG_KEY]: { - cardinality: { - field: 'host.name', - }, + }, + // retrieve all the unique hosts in the environment + [HOSTS_AGG_KEY]: { + cardinality: { + field: 'host.name', }, - // retrieve all the unique users in the environment - [USERS_AGG_KEY]: { - cardinality: { - field: 'user.name', - }, + }, + // retrieve all the unique users in the environment + [USERS_AGG_KEY]: { + cardinality: { + field: 'user.name', }, }, - size: 0, }, + size: 0, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/utils/build_requests.ts b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/utils/build_requests.ts index 3d36c5a061b65..02a55ddf31277 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/utils/build_requests.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/shared/utils/build_requests.ts @@ -22,17 +22,15 @@ export const buildAggregationSearchRequest = ( query?: QueryDslQueryContainer ): IEsSearchRequest => ({ params: { - body: { - query, - aggs: { - [key]: { - terms: { - field, - size: 1000, // setting a high size to get as close as possible to all unique values - }, + query, + aggs: { + [key]: { + terms: { + field, + size: 1000, // setting a high size to get as close as possible to all unique values }, }, - size: 0, }, + size: 0, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/cypress/support/plugin_handlers/endpoint_data_loader.ts b/x-pack/solutions/security/plugins/security_solution/public/management/cypress/support/plugin_handlers/endpoint_data_loader.ts index 4b4e9adef0ec2..01bb94a1e86ea 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/cypress/support/plugin_handlers/endpoint_data_loader.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/management/cypress/support/plugin_handlers/endpoint_data_loader.ts @@ -277,7 +277,7 @@ const waitForEndpoints = async ( const response = await esClient.search({ index, size: expectedSize, - body, + ...body, rest_total_hits_as_int: true, }); diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/attack_discovery/load.ts b/x-pack/solutions/security/plugins/security_solution/scripts/attack_discovery/load.ts index 2792692798753..f547148d74e1c 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/attack_discovery/load.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/attack_discovery/load.ts @@ -158,7 +158,7 @@ const createPipeline = async ({ esClient, log }: { esClient: Client; log: Toolin await esClient.ingest.putPipeline({ id: PIPELINE_NAME, - body: pipelineConfig, + ...pipelineConfig, }); } else { log.error('Error checking or creating ingest pipeline:'); @@ -196,12 +196,10 @@ const createAndConfigureIndex = async ({ log.info(`Creating and configuring Elasticsearch index: ${indexName}`); await esClient.indices.create({ index: indexName, - body: { - settings: { - 'index.mapping.total_fields.limit': '6000', - }, - mappings: JSON.parse(mappingData), + settings: { + 'index.mapping.total_fields.limit': '6000', }, + mappings: JSON.parse(mappingData), }); } } catch (error) { diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/delete_all_endpoint_data.ts b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/delete_all_endpoint_data.ts index 53e7056311751..47e376dcfd412 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/delete_all_endpoint_data.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/delete_all_endpoint_data.ts @@ -73,11 +73,9 @@ export const deleteAllEndpointData = async ( const deleteResponse = await esClientUnrestricted.deleteByQuery({ index: '*,.*', - body: { - query: { - query_string: { - query: queryString, - }, + query: { + query_string: { + query: queryString, }, }, ignore_unavailable: true, diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/endpoint_metadata_services.ts b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/endpoint_metadata_services.ts index cf0672b113ac7..4ab441f3e57b7 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/endpoint_metadata_services.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/endpoint_metadata_services.ts @@ -105,42 +105,40 @@ const fetchLastStreamedEndpointUpdate = async ( { index: METADATA_DATASTREAM, size: 1, - body: { - query: { - bool: { - filter: [ - { - bool: { - should: [{ term: { 'elastic.agent.id': agentId } }], - }, + query: { + bool: { + filter: [ + { + bool: { + should: [{ term: { 'elastic.agent.id': agentId } }], }, - ], - }, + }, + ], }, - // Am I doing this right? I want only the last document for the host.id that was sent - collapse: { - field: 'host.id', - inner_hits: { - name: 'most_recent', - size: 1, - sort: [{ 'event.created': 'desc' }], - }, + }, + // Am I doing this right? I want only the last document for the host.id that was sent + collapse: { + field: 'host.id', + inner_hits: { + name: 'most_recent', + size: 1, + sort: [{ 'event.created': 'desc' }], }, - aggs: { - total: { - cardinality: { - field: 'host.id', - }, + }, + aggs: { + total: { + cardinality: { + field: 'host.id', }, }, - sort: [ - { - 'event.created': { - order: 'desc', - }, - }, - ], }, + sort: [ + { + 'event.created': { + order: 'desc', + }, + }, + ], }, { ignore: [404] } ); diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/fleet_services.ts b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/fleet_services.ts index bfd2b93769fbc..1cd2dabf1cd54 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/fleet_services.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/fleet_services.ts @@ -190,9 +190,7 @@ export const checkInFleetAgent = async ( id: agentId, refresh: 'wait_for', retry_on_conflict: 5, - body: { - doc: update, - }, + doc: update, }); }; diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/stack_services.ts b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/stack_services.ts index 88da087336d3f..9511127f85cdc 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/stack_services.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/common/stack_services.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Client } from '@elastic/elasticsearch'; +import { Client, HttpConnection } from '@elastic/elasticsearch'; import type { ToolingLog } from '@kbn/tooling-log'; import type { KbnClientOptions } from '@kbn/test'; import { KbnClient } from '@kbn/test'; @@ -261,6 +261,8 @@ export const createEsClient = ({ const isHttps = new URL(url).protocol.startsWith('https'); const clientOptions: ClientOptions = { node: buildUrlWithCredentials(url, apiKey ? '' : username, apiKey ? '' : password), + Connection: HttpConnection, + requestTimeout: 30_000, }; if (isHttps && useCertForSsl) { diff --git a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts index d09a83e9dc832..927885a4ec042 100644 --- a/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts +++ b/x-pack/solutions/security/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts @@ -8,7 +8,7 @@ /* eslint-disable no-console,max-classes-per-file */ import yargs from 'yargs'; import fs from 'fs'; -import { Client, errors } from '@elastic/elasticsearch'; +import { Client, errors, HttpConnection } from '@elastic/elasticsearch'; import type { ClientOptions } from '@elastic/elasticsearch/lib/client'; import { CA_CERT_PATH } from '@kbn/dev-utils'; import type { ToolingLog } from '@kbn/tooling-log'; @@ -276,7 +276,10 @@ async function main() { }).argv; let ca: Buffer; - let clientOptions: ClientOptions; + let clientOptions: ClientOptions = { + Connection: HttpConnection, + requestTimeout: 30_000, + }; let url: string; let node: string; const logger = createToolingLogger(); @@ -297,9 +300,9 @@ async function main() { certificateAuthorities: [ca], }; - clientOptions = { node, tls: { ca: [ca] } }; + clientOptions = { ...clientOptions, node, tls: { ca: [ca] } }; } else { - clientOptions = { node: argv.node }; + clientOptions = { ...clientOptions, node: argv.node }; } let client = new Client(clientOptions); let kbnClient = new KbnClient({ ...kbnClientOptions }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/assistant/tools/open_and_acknowledged_alerts/open_and_acknowledged_alerts_tool.test.ts b/x-pack/solutions/security/plugins/security_solution/server/assistant/tools/open_and_acknowledged_alerts/open_and_acknowledged_alerts_tool.test.ts index aeda113abc2f0..a221175ed33fa 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/assistant/tools/open_and_acknowledged_alerts/open_and_acknowledged_alerts_tool.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/assistant/tools/open_and_acknowledged_alerts/open_and_acknowledged_alerts_tool.test.ts @@ -151,84 +151,82 @@ describe('OpenAndAcknowledgedAlertsTool', () => { expect(esClient.search).toHaveBeenCalledWith({ allow_no_indices: true, - body: { - _source: false, - fields: [ - { - field: '@timestamp', - include_unmapped: true, - }, - { - field: 'cloud.availability_zone', - include_unmapped: true, - }, - { - field: 'user.name', - include_unmapped: true, - }, - ], - query: { - bool: { - filter: [ - { - bool: { - filter: [ - { - bool: { - should: [ - { - match_phrase: { - 'kibana.alert.workflow_status': 'open', - }, + _source: false, + fields: [ + { + field: '@timestamp', + include_unmapped: true, + }, + { + field: 'cloud.availability_zone', + include_unmapped: true, + }, + { + field: 'user.name', + include_unmapped: true, + }, + ], + query: { + bool: { + filter: [ + { + bool: { + filter: [ + { + bool: { + should: [ + { + match_phrase: { + 'kibana.alert.workflow_status': 'open', }, - { - match_phrase: { - 'kibana.alert.workflow_status': 'acknowledged', - }, + }, + { + match_phrase: { + 'kibana.alert.workflow_status': 'acknowledged', }, - ], - minimum_should_match: 1, - }, - }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: 'now-24h', - lte: 'now', }, - }, + ], + minimum_should_match: 1, }, - ], - must: [], - must_not: [ - { - exists: { - field: 'kibana.alert.building_block_type', + }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: 'now-24h', + lte: 'now', }, }, - ], - should: [], - }, + }, + ], + must: [], + must_not: [ + { + exists: { + field: 'kibana.alert.building_block_type', + }, + }, + ], + should: [], }, - ], - }, - }, - runtime_mappings: {}, - size: 20, - sort: [ - { - 'kibana.alert.risk_score': { - order: 'desc', }, + ], + }, + }, + runtime_mappings: {}, + size: 20, + sort: [ + { + 'kibana.alert.risk_score': { + order: 'desc', }, - { - '@timestamp': { - order: 'desc', - }, + }, + { + '@timestamp': { + order: 'desc', }, - ], - }, + }, + ], ignore_unavailable: true, index: ['alerts-index'], }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts index 29a9d5e547825..5087000e2a5a6 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts @@ -6,7 +6,7 @@ */ import type { TransportResult } from '@elastic/elasticsearch'; -import type { TransformGetTransformStatsResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { TransformGetTransformStatsResponse } from '@elastic/elasticsearch/lib/api/types'; import { CheckMetadataTransformsTask, TYPE, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.ts index cf5f19ab9741f..3a05b22183118 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.ts @@ -9,7 +9,7 @@ import type { TransportResult } from '@elastic/elasticsearch'; import type { TransformGetTransformStatsResponse, TransformGetTransformStatsTransformStats, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { CoreSetup, ElasticsearchClient, Logger } from '@kbn/core/server'; import type { ConcreteTaskInstance, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/mocks/utils.mock.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/mocks/utils.mock.ts index d8d043c29ec67..07784bd6e7c0e 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/mocks/utils.mock.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/mocks/utils.mock.ts @@ -58,7 +58,7 @@ export const applyEsClientSearchMock = ({ esClientMock.closePointInTime.mockImplementation(async (...args) => { const closePitResponse = { succeeded: true, num_freed: 1 }; const options = args[0]; - const pitId = 'id' in options ? options.id : 'body' in options ? options.body?.id : undefined; + const pitId = options.id; if (pitId) { if (openedPitIds.has(pitId)) { diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/response_actions.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/response_actions.test.ts index 80a079c0cccda..c7d7726d796be 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/response_actions.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/response_actions.test.ts @@ -8,7 +8,7 @@ import { Subject } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ILicense } from '@kbn/licensing-plugin/common/types'; import { licenseMock } from '@kbn/licensing-plugin/common/licensing.mock'; import type { License } from '@kbn/licensing-plugin/common/license'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/status.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/status.test.ts index d7b8824745cd0..e81d502ac16f2 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/status.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/actions/status.test.ts @@ -99,7 +99,6 @@ describe('Endpoint Pending Action Summary API', () => { endpointResponses: LogsEndpointActionResponse[] ) => { esClientMock.asInternalUser.search.mockResponseImplementation((req = {}) => { - // @ts-expect-error size not defined as top level property when using typesWithBodyKey const size = req.size ? req.size : 10; const items: any[] = []; let index = Array.isArray(req.index) ? req.index.join() : req.index; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts index 6010c56557273..e72503981f038 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts @@ -62,11 +62,11 @@ import type { } from '@kbn/core-elasticsearch-client-server-mocks'; import { EndpointHostNotFoundError } from '../../services/metadata'; import { FleetAgentGenerator } from '../../../../common/endpoint/data_generators/fleet_agent_generator'; -import type { TransformGetTransformStatsResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { TransformGetTransformStatsResponse } from '@elastic/elasticsearch/lib/api/types'; import { getEndpointAuthzInitialStateMock } from '../../../../common/endpoint/service/authz/mocks'; import type { VersionedRouteConfig } from '@kbn/core-http-server'; import type { SecuritySolutionPluginRouterMock } from '../../../mocks'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; describe('test endpoint routes', () => { let routerMock: SecuritySolutionPluginRouterMock; @@ -178,8 +178,7 @@ describe('test endpoint routes', () => { expect(esSearchMock).toHaveBeenCalledTimes(1); expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); - // @ts-expect-error partial definition - expect(esSearchMock.mock.calls[0][0]?.body?.query).toEqual({ + expect(esSearchMock.mock.calls[0][0]?.query).toEqual({ bool: { must: [ { diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts index edc7861d9d3af..1d22ff8141a1b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts @@ -27,7 +27,7 @@ describe('query builder', () => { const mockID = 'AABBCCDD-0011-2233-AA44-DEADBEEF8899'; const query = getESQueryHostMetadataByID(mockID); - expect(get(query, 'body.query.bool.filter.0.bool.should')).toContainEqual({ + expect(get(query, 'query.bool.filter.0.bool.should')).toContainEqual({ term: { 'agent.id': mockID }, }); }); @@ -36,7 +36,7 @@ describe('query builder', () => { const mockID = 'AABBCCDD-0011-2233-AA44-DEADBEEF8899'; const query = getESQueryHostMetadataByID(mockID); - expect(get(query, 'body.query.bool.filter.0.bool.should')).toContainEqual({ + expect(get(query, 'query.bool.filter.0.bool.should')).toContainEqual({ term: { 'HostDetails.agent.id': mockID }, }); }); @@ -102,7 +102,7 @@ describe('query builder', () => { ], }, }; - expect(query.body.query).toEqual(expected); + expect(query.query).toEqual(expected); }); it('adds `status` runtime field', async () => { @@ -112,7 +112,7 @@ describe('query builder', () => { [] ); - expect(query.body.runtime_mappings).toHaveProperty('status'); + expect(query.runtime_mappings).toHaveProperty('status'); }); it('adds `last_checkin` runtime field', async () => { @@ -122,7 +122,7 @@ describe('query builder', () => { [] ); - expect(query.body.runtime_mappings).toHaveProperty('last_checkin'); + expect(query.runtime_mappings).toHaveProperty('last_checkin'); }); it('correctly builds query', async () => { @@ -137,7 +137,7 @@ describe('query builder', () => { ['test-endpoint-policy-id'] ); const expected = expectedCompleteUnitedIndexQuery; - expect(query.body.query).toEqual(expected); + expect(query.query).toEqual(expected); }); describe('sorting', () => { @@ -147,7 +147,7 @@ describe('query builder', () => { pageSize: 10, }); - expect(query.body.sort).toEqual([ + expect(query.sort).toEqual([ { 'united.agent.enrolled_at': { order: 'desc', unmapped_type: 'date' } }, ]); }); @@ -165,7 +165,7 @@ describe('query builder', () => { sortDirection: 'asc', }); - expect(query.body.sort).toEqual([{ [mappedField]: 'asc' }]); + expect(query.sort).toEqual([{ [mappedField]: 'asc' }]); }); it.each` @@ -180,9 +180,7 @@ describe('query builder', () => { sortDirection: 'asc', }); - expect(query.body.sort).toEqual([ - { [mappedField]: { order: 'asc', unmapped_type: 'date' } }, - ]); + expect(query.sort).toEqual([{ [mappedField]: { order: 'asc', unmapped_type: 'date' } }]); }); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts index e51655010b40c..d84a59a9e12a4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { buildAgentStatusRuntimeField } from '@kbn/fleet-plugin/server'; import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; @@ -80,24 +80,22 @@ const getUnitedMetadataSortMethod = ( export function getESQueryHostMetadataByID(agentID: string): estypes.SearchRequest { return { - body: { - query: { - bool: { - filter: [ - { - bool: { - should: [ - { term: { 'agent.id': agentID } }, - { term: { 'HostDetails.agent.id': agentID } }, - ], - }, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { term: { 'agent.id': agentID } }, + { term: { 'HostDetails.agent.id': agentID } }, + ], }, - ], - }, + }, + ], }, - sort: MetadataSortMethod, - size: 1, }, + sort: MetadataSortMethod, + size: 1, index: metadataCurrentIndexPattern, }; } @@ -106,50 +104,46 @@ export function getESQueryHostMetadataByFleetAgentIds( fleetAgentIds: string[] ): estypes.SearchRequest { return { - body: { - query: { - bool: { - filter: [ - { - bool: { - should: [{ terms: { 'elastic.agent.id': fleetAgentIds } }], - }, + query: { + bool: { + filter: [ + { + bool: { + should: [{ terms: { 'elastic.agent.id': fleetAgentIds } }], }, - ], - }, + }, + ], }, - sort: MetadataSortMethod, }, + sort: MetadataSortMethod, index: metadataCurrentIndexPattern, }; } -export function getESQueryHostMetadataByIDs(agentIDs: string[]) { +export function getESQueryHostMetadataByIDs(agentIDs: string[]): estypes.SearchRequest { return { - body: { - query: { - bool: { - filter: [ - { - bool: { - should: [ - { terms: { 'agent.id': agentIDs } }, - { terms: { 'HostDetails.agent.id': agentIDs } }, - ], - }, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { terms: { 'agent.id': agentIDs } }, + { terms: { 'HostDetails.agent.id': agentIDs } }, + ], }, - ], - }, + }, + ], }, - sort: MetadataSortMethod, }, + sort: MetadataSortMethod, index: metadataCurrentIndexPattern, }; } const lastCheckinRuntimeField = { last_checkin: { - type: 'date', + type: 'date' as const, script: { lang: 'painless', source: @@ -158,14 +152,10 @@ const lastCheckinRuntimeField = { }, }; -interface BuildUnitedIndexQueryResponse { - body: { - query: Record; - track_total_hits: boolean; - sort: estypes.SortCombinations[]; - runtime_mappings: Record; - fields?: string[]; - }; +interface BuildUnitedIndexQueryResponse extends estypes.SearchRequest { + track_total_hits: boolean; + sort: estypes.SortCombinations[]; + fields?: string[]; from: number; size: number; index: string; @@ -217,7 +207,7 @@ export async function buildUnitedIndexQuery( }, }; - let query: BuildUnitedIndexQueryResponse['body']['query'] = idFilter; + let query: BuildUnitedIndexQueryResponse['query'] = idFilter; if (statusesKuery || kuery) { const kqlQuery = toElasticsearchQuery(fromKueryExpression(kuery ?? '')); @@ -241,13 +231,11 @@ export async function buildUnitedIndexQuery( const fields = Object.keys(runtimeMappings); return { - body: { - query, - track_total_hits: true, - sort: getUnitedMetadataSortMethod(sortField as EndpointSortableField, sortDirection), - fields, - runtime_mappings: runtimeMappings, - }, + query, + track_total_hits: true, + sort: getUnitedMetadataSortMethod(sortField as EndpointSortableField, sortDirection), + fields, + runtime_mappings: runtimeMappings, from: page * pageSize, size: pageSize, index: METADATA_UNITED_INDEX, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/query_strategies.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/query_strategies.ts index 9f4a824f09afb..8f7dd738e5156 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/query_strategies.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/query_strategies.ts @@ -5,10 +5,7 @@ * 2.0. */ -import type { - SearchResponse, - SearchTotalHits, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchResponse, SearchTotalHits } from '@elastic/elasticsearch/lib/api/types'; import type { HostMetadata } from '../../../../../common/endpoint/types'; import type { HostListQueryResult, HostQueryResult } from '../../../types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/test_support.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/test_support.ts index 43780d8f106fe..ad6ad27d8f503 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/test_support.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/metadata/support/test_support.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Agent } from '@kbn/fleet-plugin/common'; import { METADATA_UNITED_INDEX } from '../../../../../common/endpoint/constants'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts index b7aea568b6cb5..724194b2c65d9 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts @@ -18,7 +18,7 @@ import { httpServerMock, savedObjectsClientMock, } from '@kbn/core/server/mocks'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { GetHostPolicyResponse, HostPolicyResponse } from '../../../../common/endpoint/types'; import { EndpointDocGenerator } from '../../../../common/endpoint/generate_data'; import { requestContextMock } from '../../../lib/detection_engine/routes/__mocks__'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.test.ts index f95e4c4c2d1d6..d08653f2f49c2 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.test.ts @@ -32,7 +32,7 @@ describe('Policy Response Services', () => { it('queries for the correct host', async () => { const agentId = 'f757d3c0-e874-11ea-9ad9-015510b487f4'; const query = getESQueryPolicyResponseByAgentID(agentId, 'anyindex'); - expect(query.body?.query?.bool?.filter).toEqual({ term: { 'agent.id': agentId } }); + expect(query.query?.bool?.filter).toEqual({ term: { 'agent.id': agentId } }); }); it('filters out initial policy by ID', async () => { @@ -40,7 +40,7 @@ describe('Policy Response Services', () => { 'f757d3c0-e874-11ea-9ad9-015510b487f4', 'anyindex' ); - expect(query.body?.query?.bool?.must_not).toEqual({ + expect(query.query?.bool?.must_not).toEqual({ term: { 'Endpoint.policy.applied.id': '00000000-0000-0000-0000-000000000000', }, @@ -72,13 +72,11 @@ describe('Policy Response Services', () => { expect(esClientMock.search).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: expect.objectContaining({ - bool: expect.objectContaining({ - filter: expect.objectContaining({ - term: expect.objectContaining({ - 'agent.id': '1-2-3', - }), + query: expect.objectContaining({ + bool: expect.objectContaining({ + filter: expect.objectContaining({ + term: expect.objectContaining({ + 'agent.id': '1-2-3', }), }), }), diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.ts index eb36bdf015b9f..38e314b239a91 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/policy/service.ts @@ -20,30 +20,28 @@ export const getESQueryPolicyResponseByAgentID = ( index: string ): ISearchRequestParams => { return { - body: { - query: { - bool: { - filter: { - term: { - 'agent.id': agentID, - }, - }, - must_not: { - term: { - 'Endpoint.policy.applied.id': INITIAL_POLICY_ID, - }, + query: { + bool: { + filter: { + term: { + 'agent.id': agentID, }, }, - }, - sort: [ - { - 'event.created': { - order: 'desc', + must_not: { + term: { + 'Endpoint.policy.applied.id': INITIAL_POLICY_ID, }, }, - ], - size: 1, + }, }, + sort: [ + { + 'event.created': { + order: 'desc', + }, + }, + ], + size: 1, index, }; }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/handler.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/handler.ts index 80fa208f1889a..75ca41b3f7c92 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/handler.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/handler.ts @@ -34,21 +34,19 @@ export function handleEntities( const queryResponse = await esClient.asCurrentUser.search({ ignore_unavailable: true, index: indices, - body: { - // only return 1 match at most - size: 1, - query: { - bool: { - filter: [ - ...createSharedFilters({ excludeColdAndFrozenTiers }), - { - // only return documents with the matching _id - ids: { - values: _id, - }, + // only return 1 match at most + size: 1, + query: { + bool: { + filter: [ + ...createSharedFilters({ excludeColdAndFrozenTiers }), + { + // only return documents with the matching _id + ids: { + values: _id, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/utils/build_resolver_entity.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/utils/build_resolver_entity.ts index 7f8e4cbeb381a..091eaa3d270a3 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/utils/build_resolver_entity.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/entity/utils/build_resolver_entity.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ExperimentalFeatures } from '../../../../../../common'; import { getFieldAsString, getSupportedSchemas } from './supported_schemas'; import type { ResolverEntityIndex } from '../../../../../../common/endpoint/types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts index dcce3bb64d298..63c6a90a18d39 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IScopedClusterClient } from '@kbn/core/server'; import type { JsonObject, JsonValue } from '@kbn/utility-types'; import type { FieldsObject } from '../../../../../../common/endpoint/types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_details_by_id.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_details_by_id.test.ts index 805cf8d8c041d..2ab1e3fc1709a 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_details_by_id.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_details_by_id.test.ts @@ -7,7 +7,7 @@ import type { ElasticsearchClientMock } from '@kbn/core/server/mocks'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EndpointActionResponse, LogsEndpointAction, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_list.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_list.test.ts index 489b306d69fd5..9d35c8e7bcd91 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_list.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/action_list.test.ts @@ -7,7 +7,7 @@ import type { ElasticsearchClientMock } from '@kbn/core/server/mocks'; import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EndpointActionResponse, LogsEndpointAction, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts index 25fcb30be4949..6c0612c65f220 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/crowdstrike/crowdstrike_actions_client.ts @@ -137,11 +137,9 @@ export class CrowdstrikeActionsClient extends ResponseActionsClientImpl { index: ['logs-crowdstrike*'], size: 1, _source: ['host.hostname', 'host.name'], - body: { - query: { - bool: { - filter: [{ term: { 'device.id': agentId } }], - }, + query: { + bool: { + filter: [{ term: { 'device.id': agentId } }], }, }, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/lib/base_response_actions_client.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/lib/base_response_actions_client.test.ts index 83e2d5f1cfefb..cfa031280743f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/lib/base_response_actions_client.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/lib/base_response_actions_client.test.ts @@ -28,8 +28,7 @@ import type { CasesClientMock } from '@kbn/cases-plugin/server/client/mocks'; import type { CasesByAlertIDParams } from '@kbn/cases-plugin/server/client/cases/get'; import type { Logger } from '@kbn/logging'; import { getActionDetailsById as _getActionDetailsById } from '../../action_details_by_id'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { TransportResult } from '@elastic/elasticsearch'; +import type { estypes, TransportResult } from '@elastic/elasticsearch'; import { ENDPOINT_ACTION_RESPONSES_INDEX, ENDPOINT_ACTION_RESPONSES_INDEX_PATTERN, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts index 97973b0638d7a..180e4e5d3f1fc 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/clients/mocks.ts @@ -17,8 +17,7 @@ import type { CasesClientMock } from '@kbn/cases-plugin/server/client/mocks'; import { createCasesClientMock } from '@kbn/cases-plugin/server/client/mocks'; import { elasticsearchServiceMock } from '@kbn/core-elasticsearch-server-mocks'; import { merge } from 'lodash'; -import type * as esTypes from '@elastic/elasticsearch/lib/api/types'; -import type { TransportResult } from '@elastic/elasticsearch'; +import type { TransportResult, estypes } from '@elastic/elasticsearch'; import type { AttachmentsSubClient } from '@kbn/cases-plugin/server/client/attachments/client'; import { loggingSystemMock } from '@kbn/core-logging-server-mocks'; import type { DeeplyMockedKeys } from '@kbn/utility-types-jest'; @@ -128,9 +127,9 @@ const createConstructorOptionsMock = (): Required> = {} -): TransportResult => { - const responseDoc: TransportResult = { + overrides: DeepPartial> = {} +): TransportResult => { + const responseDoc: TransportResult = { body: { _id: 'indexed-1-2-3', _index: 'some-index', diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/mocks.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/mocks.ts index 9911ae781c20f..aeb29d030bf6c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/mocks.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/mocks.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClientMock } from '@kbn/core/server/mocks'; import { AGENT_ACTIONS_RESULTS_INDEX } from '@kbn/fleet-plugin/common'; import { Readable } from 'stream'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/fetch_action_responses.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/fetch_action_responses.ts index 54396ecb9e86b..f2c472be64d8c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/fetch_action_responses.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/fetch_action_responses.ts @@ -7,7 +7,7 @@ import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import { AGENT_ACTIONS_RESULTS_INDEX } from '@kbn/fleet-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EndpointActionResponse, LogsEndpointActionResponse, diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/get_action_agent_type.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/get_action_agent_type.ts index caf97b2b0e4f5..d53c6f961abe5 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/get_action_agent_type.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/get_action_agent_type.ts @@ -22,11 +22,9 @@ export const getActionAgentType = async ( const response = await esClient .search({ index: ENDPOINT_ACTIONS_INDEX, - body: { - query: { - bool: { - filter: [{ term: { action_id: actionId } }], - }, + query: { + bool: { + filter: [{ term: { action_id: actionId } }], }, }, _source: ['EndpointActions.input_type'], diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.test.ts index 69c66f90e4286..9fe23d6302a77 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { EndpointActionGenerator } from '../../../../../common/endpoint/data_generators/endpoint_action_generator'; import { FleetActionGenerator } from '../../../../../common/endpoint/data_generators/fleet_action_generator'; import type { NormalizedActionRequest } from './utils'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.ts index 42805e49f894f..c79812c43729c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/actions/utils/utils.ts @@ -6,7 +6,7 @@ */ import type { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EcsError } from '@elastic/ecs'; import moment from 'moment/moment'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts index 8a4022771d69c..e35998848d70d 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts @@ -177,9 +177,9 @@ describe('EndpointMetadataService', () => { packagePolicyIds ); - expect(unitedIndexQuery.body.runtime_mappings.status).toBeDefined(); + expect(unitedIndexQuery.runtime_mappings?.status).toBeDefined(); // @ts-expect-error runtime_mappings is not typed - unitedIndexQuery.body.runtime_mappings.status.script.source = expect.any(String); + unitedIndexQuery.runtime_mappings.status.script.source = expect.any(String); expect(esClient.search).toBeCalledWith(unitedIndexQuery); expect(agentPolicyServiceMock.getByIds).toBeCalledWith(expect.anything(), agentPolicyIds); diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts index 1ce77561b7904..6176168074a63 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts @@ -118,7 +118,6 @@ export class EndpointMetadataService { async findHostMetadataForFleetAgents(fleetAgentIds: string[]): Promise { const query = getESQueryHostMetadataByFleetAgentIds(fleetAgentIds); - // @ts-expect-error `size` not defined as top level property when using `typesWithBodyKey` query.size = fleetAgentIds.length; const searchResult = await this.esClient diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.test.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.test.ts index a9b71a3017209..f4ecaaf875061 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.test.ts @@ -293,7 +293,7 @@ describe('SecurityWorkflowInsightsService', () => { expect(esClient.index).toHaveBeenCalledWith({ index: DATA_STREAM_NAME, id: generateInsightId(insight), - body: insight, + document: insight, refresh: 'wait_for', op_type: 'create', }); @@ -362,7 +362,7 @@ describe('SecurityWorkflowInsightsService', () => { expect(esClient.update).toHaveBeenCalledWith({ index: indexName, id: insightId, - body: { doc: insight }, + doc: insight, refresh: 'wait_for', }); }); @@ -391,81 +391,79 @@ describe('SecurityWorkflowInsightsService', () => { expect(esClient.search).toHaveBeenCalledTimes(1); expect(esClient.search).toHaveBeenCalledWith({ index: DATA_STREAM_NAME, - body: { - query: { - bool: { - must: [ - { - terms: { - _id: ['id1', 'id2'], - }, + query: { + bool: { + must: [ + { + terms: { + _id: ['id1', 'id2'], }, - { - terms: { - categories: ['endpoint'], - }, + }, + { + terms: { + categories: ['endpoint'], }, - { - terms: { - types: ['incompatible_antivirus'], - }, + }, + { + terms: { + types: ['incompatible_antivirus'], }, - { - nested: { - path: 'source', - query: { - terms: { - 'source.type': ['llm-connector'], - }, + }, + { + nested: { + path: 'source', + query: { + terms: { + 'source.type': ['llm-connector'], }, }, }, - { - nested: { - path: 'source', - query: { - terms: { - 'source.id': ['source-id1', 'source-id2'], - }, + }, + { + nested: { + path: 'source', + query: { + terms: { + 'source.id': ['source-id1', 'source-id2'], }, }, }, - { - nested: { - path: 'target', - query: { - terms: { - 'target.type': ['endpoint'], - }, + }, + { + nested: { + path: 'target', + query: { + terms: { + 'target.type': ['endpoint'], }, }, }, - { - nested: { - path: 'target', - query: { - terms: { - 'target.ids': ['target-id1', 'target-id2'], - }, + }, + { + nested: { + path: 'target', + query: { + terms: { + 'target.ids': ['target-id1', 'target-id2'], }, }, }, - { - nested: { - path: 'action', - query: { - terms: { - 'action.type': ['refreshed', 'remediated'], - }, + }, + { + nested: { + path: 'action', + query: { + terms: { + 'action.type': ['refreshed', 'remediated'], }, }, }, - ], - }, + }, + ], }, - size: searchParams.size, - from: searchParams.from, }, + size: searchParams.size, + from: searchParams.from, }); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.ts b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.ts index 29e060298214b..e3559df9c7e0f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/endpoint/services/workflow_insights/index.ts @@ -166,7 +166,7 @@ class SecurityWorkflowInsightsService { const response = await this.esClient.index({ index: DATA_STREAM_NAME, id, - body: insight, + document: insight, refresh: 'wait_for', op_type: 'create', }); @@ -194,7 +194,7 @@ class SecurityWorkflowInsightsService { const response = await this.esClient.update({ index, id, - body: { doc: insight }, + doc: insight, refresh: 'wait_for', }); @@ -210,15 +210,13 @@ class SecurityWorkflowInsightsService { const termFilters = params ? buildEsQueryParams(params) : []; const response = await this.esClient.search({ index: DATA_STREAM_NAME, - body: { - query: { - bool: { - must: termFilters, - }, + query: { + bool: { + must: termFilters, }, - size, - from, }, + size, + from, }); return response?.hits?.hits ?? []; diff --git a/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/helpers.ts b/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/helpers.ts index 3f25322b9e017..5324f011ebb42 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/helpers.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/helpers.ts @@ -127,11 +127,11 @@ export async function bulkInsert( data: unknown[], ids: string[] = [] ): Promise { - const bulk = data.flatMap((d, i) => { + const operations = data.flatMap((d, i) => { const _id = ids[i] ?? uuidGen(); return [{ create: { _index: index, _id } }, d]; }); - await esClient.bulk({ body: bulk, refresh: 'wait_for' }).catch(() => {}); + await esClient.bulk({ operations, refresh: 'wait_for' }).catch(() => {}); } export function updateTimestamps(data: object[]): object[] { diff --git a/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/telemetry_helpers.ts b/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/telemetry_helpers.ts index 8dc9f1cbbca49..a8af8d52190ea 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/telemetry_helpers.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/integration_tests/lib/telemetry_helpers.ts @@ -150,7 +150,7 @@ export function getTelemetryTask( export async function createMockedEndpointAlert(esClient: ElasticsearchClient) { const index = `${DEFAULT_DIAGNOSTIC_INDEX_PATTERN.replace('-*', '')}-001`; - await esClient.indices.create({ index, body: { settings: { hidden: true } } }); + await esClient.indices.create({ index, settings: { hidden: true } }); if (mockEndpointAlert['event']) { mockEndpointAlert['event']['ingested'] = new Date().toISOString(); @@ -242,10 +242,8 @@ export async function cleanupMockedAlerts( await esClient .deleteByQuery({ index: alias[0], - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }) .catch(() => { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.test.ts index 6cc2a9baef062..a6e1f82ba7392 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.test.ts @@ -33,12 +33,10 @@ describe('createMigration', () => { expect(esClient.reindex).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - source: { - index: 'my-signals-index', - size: reindexOptions.size, - }, - }), + source: { + index: 'my-signals-index', + size: reindexOptions.size, + }, requests_per_second: reindexOptions.requests_per_second, slices: reindexOptions.slices, }) diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.ts index 8bc38b1ecdf94..cb21bfe5d334e 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration.ts @@ -49,44 +49,42 @@ export const createMigration = async ({ const { size, ...reindexQueryOptions } = reindexOptions; const response = await esClient.reindex({ - body: { - dest: { index: migrationIndex }, - source: { index, size }, - script: { - lang: 'painless', - source: ` - if (ctx._source.signal._meta == null) { - ctx._source.signal._meta = [:]; - } - ctx._source.signal._meta.version = params.version; + dest: { index: migrationIndex }, + source: { index, size }, + script: { + lang: 'painless', + source: ` + if (ctx._source.signal._meta == null) { + ctx._source.signal._meta = [:]; + } + ctx._source.signal._meta.version = params.version; - // migrate enrichments before 7.15 to ECS 1.11 - if (ctx._source.signal?.rule?.type == "threat_match" && - ctx._source.threat?.indicator instanceof List && - ctx._source.threat?.enrichments == null) { - ctx._source.threat.enrichments = []; - for (indicator in ctx._source.threat.indicator) { - def enrichment = [:]; - enrichment.indicator = indicator; - enrichment.indicator.reference = indicator.event?.reference; - enrichment.matched = indicator.matched; - enrichment.indicator.remove("matched"); - ctx._source.threat.enrichments.add(enrichment); - } - ctx._source.threat.remove("indicator"); + // migrate enrichments before 7.15 to ECS 1.11 + if (ctx._source.signal?.rule?.type == "threat_match" && + ctx._source.threat?.indicator instanceof List && + ctx._source.threat?.enrichments == null) { + ctx._source.threat.enrichments = []; + for (indicator in ctx._source.threat.indicator) { + def enrichment = [:]; + enrichment.indicator = indicator; + enrichment.indicator.reference = indicator.event?.reference; + enrichment.matched = indicator.matched; + enrichment.indicator.remove("matched"); + ctx._source.threat.enrichments.add(enrichment); } + ctx._source.threat.remove("indicator"); + } - // migrate status - if(ctx._source.signal?.status == "in-progress") { - ctx._source.signal.status = "acknowledged"; - } - if(ctx._source['kibana.alert.workflow_status'] == "in-progress") { - ctx._source['kibana.alert.workflow_status'] = "acknowledged"; - } - `, - params: { - version, - }, + // migrate status + if(ctx._source.signal?.status == "in-progress") { + ctx._source.signal.status = "acknowledged"; + } + if(ctx._source['kibana.alert.workflow_status'] == "in-progress") { + ctx._source['kibana.alert.workflow_status'] = "acknowledged"; + } + `, + params: { + version, }, }, ...reindexQueryOptions, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_index.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_index.ts index c2a625abd8112..77e4b3c872879 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_index.ts @@ -34,18 +34,16 @@ export const createMigrationIndex = async ({ const response = await esClient.indices.create({ index: destinationIndexName, - body: { - settings: { - index: { - lifecycle: { - indexing_complete: true, - }, + settings: { + index: { + lifecycle: { + indexing_complete: true, }, }, - mappings: { - _meta: { - version, - }, + }, + mappings: { + _meta: { + version, }, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_latest_index_template_version.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_latest_index_template_version.test.ts index ea48c51aabcc5..852b64e400f94 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_latest_index_template_version.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_latest_index_template_version.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { IndicesGetIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { IndicesGetIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/types'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { getLatestIndexTemplateVersion } from './get_latest_index_template_version'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts index 5bed307b69164..cbf9bacb3de8b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts @@ -53,18 +53,16 @@ export const getSignalVersionsByIndex = async ({ const response = await esClient.search({ index, size: 0, - body: { - aggs: { - signals_indices: { - terms: { - field: '_index', - }, - aggs: { - signal_versions: { - terms: { - field: 'signal._meta.version', - missing: 0, - }, + aggs: { + signals_indices: { + terms: { + field: '_index', + }, + aggs: { + signal_versions: { + terms: { + field: 'signal._meta.version', + missing: 0, }, }, }, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signals_indices_in_range.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signals_indices_in_range.ts index bc178c71c183e..51e3456e3aed1 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signals_indices_in_range.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/get_signals_indices_in_range.ts @@ -44,31 +44,29 @@ export const getSignalsIndicesInRange = async ({ const response = await esClient.search({ index, - body: { - aggs: { - indexes: { - terms: { - field: '_index', - }, + aggs: { + indexes: { + terms: { + field: '_index', }, }, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: from, - lte: 'now', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: from, + lte: 'now', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, }); const aggs = response.aggregations as IndexesResponse['aggregations']; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts index f32aee3ff32ed..1c2abda01e633 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts @@ -57,7 +57,7 @@ export const ensureMigrationCleanupPolicy = async ({ if (!policyExists) { await esClient.ilm.putLifecycle({ name: policy, - body: migrationCleanupPolicy, + ...migrationCleanupPolicy, }); } }; @@ -85,7 +85,7 @@ export const applyMigrationCleanupPolicy = async ({ }): Promise => { await esClient.indices.putSettings({ index, - body: { + settings: { lifecycle: { name: getMigrationCleanupPolicyName(alias), }, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/replace_signals_index_alias.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/replace_signals_index_alias.ts index 984707959005c..5996e3a8ec98f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/replace_signals_index_alias.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/migrations/replace_signals_index_alias.ts @@ -35,19 +35,15 @@ export const replaceSignalsIndexAlias = async ({ legacySiemSignalsAlias: string; }): Promise => { await esClient.indices.updateAliases({ - body: { - actions: [ - { remove: { index: oldIndex, alias } }, - { add: { index: newIndex, alias, is_write_index: false } }, - ], - }, + actions: [ + { remove: { index: oldIndex, alias } }, + { add: { index: newIndex, alias, is_write_index: false } }, + ], }); await esClient.indices.updateAliases({ - body: { - actions: [ - { remove: { index: oldIndex, alias: legacySiemSignalsAlias } }, - { add: { index: newIndex, alias: legacySiemSignalsAlias, is_write_index: false } }, - ], - }, + actions: [ + { remove: { index: oldIndex, alias: legacySiemSignalsAlias } }, + { add: { index: newIndex, alias: legacySiemSignalsAlias, is_write_index: false } }, + ], }); }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts index 4ed9b44976f2f..5a6d31ad95401 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SavedObjectsFindResponse } from '@kbn/core/server'; import { ALERT_WORKFLOW_STATUS } from '@kbn/rule-data-utils'; import { ruleTypeMappings } from '@kbn/securitysolution-rules'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts index 5257486dcb53a..5337c1333fbde 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts @@ -6,7 +6,7 @@ */ import { chunk, get } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ElasticsearchClient, IKibanaResponse } from '@kbn/core/server'; import { transformError, @@ -218,7 +218,7 @@ const addIndexAliases = async ({ }; }), }; - await esClient.indices.updateAliases({ body: aliasActions }); + await esClient.indices.updateAliases(aliasActions); }; /** diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts index a1569e8bcab07..eee9009ca00d4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts @@ -87,10 +87,8 @@ describe('set signal status', () => { ); expect(context.core.elasticsearch.client.asCurrentUser.updateByQuery).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: expect.objectContaining({ - bool: { filter: typicalSetStatusSignalByQueryPayload().query }, - }), + query: expect.objectContaining({ + bool: { filter: typicalSetStatusSignalByQueryPayload().query }, }), }) ); @@ -103,9 +101,7 @@ describe('set signal status', () => { ); expect(context.core.elasticsearch.client.asCurrentUser.updateByQuery).toHaveBeenCalledWith( expect.objectContaining({ - body: expect.objectContaining({ - query: { bool: { filter: { terms: { _id: ['somefakeid1', 'somefakeid2'] } } } }, - }), + query: { bool: { filter: { terms: { _id: ['somefakeid1', 'somefakeid2'] } } } }, }) ); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts index 5438db042e7df..ba27b88626e04 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts @@ -134,12 +134,10 @@ const updateSignalsStatusByIds = async ( esClient.updateByQuery({ index: `${DEFAULT_ALERTS_INDEX}-${spaceId}`, refresh: true, - body: { - script: getUpdateSignalStatusScript(status, user), - query: { - bool: { - filter: { terms: { _id: signalsId } }, - }, + script: getUpdateSignalStatusScript(status, user), + query: { + bool: { + filter: { terms: { _id: signalsId } }, }, }, ignore_unavailable: true, @@ -162,12 +160,10 @@ const updateSignalsStatusByQuery = async ( index: `${DEFAULT_ALERTS_INDEX}-${spaceId}`, conflicts: options.conflicts, refresh: true, - body: { - script: getUpdateSignalStatusScript(status, user), - query: { - bool: { - filter: query, - }, + script: getUpdateSignalStatusScript(status, user), + query: { + bool: { + filter: query, }, }, ignore_unavailable: true, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts index 8ae230d65506b..4c1d562be65ef 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts @@ -47,9 +47,7 @@ describe('query for signal', () => { expect(response.status).toEqual(200); expect(context.core.elasticsearch.client.asCurrentUser.search).toHaveBeenCalledWith( - expect.objectContaining({ - body: typicalSignalsQuery(), - }) + expect.objectContaining(typicalSignalsQuery()) ); }); @@ -75,7 +73,7 @@ describe('query for signal', () => { expect(response.status).toEqual(200); expect(context.core.elasticsearch.client.asCurrentUser.search).toHaveBeenCalledWith( - expect.objectContaining({ body: typicalSignalsQueryAggs(), ignore_unavailable: true }) + expect.objectContaining({ ...typicalSignalsQueryAggs(), ignore_unavailable: true }) ); }); @@ -88,10 +86,8 @@ describe('query for signal', () => { expect(response.status).toEqual(200); expect(context.core.elasticsearch.client.asCurrentUser.search).toHaveBeenCalledWith( expect.objectContaining({ - body: { - ...typicalSignalsQuery(), - ...typicalSignalsQueryAggs(), - }, + ...typicalSignalsQuery(), + ...typicalSignalsQueryAggs(), }) ); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts index f49eaad74e490..2092ff935a52b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts @@ -5,10 +5,13 @@ * 2.0. */ -import type { MappingRuntimeFields, Sort } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { + AggregationsAggregationContainer, + MappingRuntimeFields, + Sort, +} from '@elastic/elasticsearch/lib/api/types'; import { transformError } from '@kbn/securitysolution-es-utils'; import type { IRuleDataClient } from '@kbn/rule-registry-plugin/server'; -import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import { buildRouteValidationWithZod } from '@kbn/zod-helpers'; import { SearchAlertsRequestBody } from '../../../../../common/api/detection_engine/signals'; import type { SecuritySolutionPluginRouter } from '../../../../types'; @@ -64,16 +67,14 @@ export const querySignalsRoute = ( const indexPattern = ruleDataClient?.indexNameWithNamespace(spaceId); const result = await esClient.search({ index: indexPattern, - body: { - query, - aggs: aggs as Record, - _source, - fields, - track_total_hits, - size, - runtime_mappings: runtime_mappings as MappingRuntimeFields, - sort: sort as Sort, - }, + query, + aggs: aggs as Record, + _source, + fields, + track_total_hits, + size, + runtime_mappings: runtime_mappings as MappingRuntimeFields, + sort: sort as Sort, ignore_unavailable: true, }); return response.ok({ body: result }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_assignees_route.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_assignees_route.ts index 9e5547e03c7e6..5fee6554a1400 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_assignees_route.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_assignees_route.ts @@ -94,12 +94,10 @@ export const setAlertAssigneesRoute = (router: SecuritySolutionPluginRouter) => const body = await esClient.updateByQuery({ index: `${DEFAULT_ALERTS_INDEX}-${spaceId}`, refresh: true, - body: { - script: painlessScript, - query: { - bool: { - filter: { terms: { _id: ids } }, - }, + script: painlessScript, + query: { + bool: { + filter: { terms: { _id: ids } }, }, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_tags_route.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_tags_route.ts index 3fbd21c57ffef..19b7f309ce126 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_tags_route.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/routes/signals/set_alert_tags_route.ts @@ -99,12 +99,10 @@ export const setAlertTagsRoute = (router: SecuritySolutionPluginRouter) => { const body = await esClient.updateByQuery({ index: `${DEFAULT_ALERTS_INDEX}-${spaceId}`, refresh: true, - body: { - script: painlessScript, - query: { - bool: { - filter: { terms: { _id: ids } }, - }, + script: painlessScript, + query: { + bool: { + filter: { terms: { _id: ids } }, }, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.test.ts index ab0e4cd64fceb..9c6ee7918a09c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.test.ts @@ -24,38 +24,36 @@ describe('buildSignalsSearchQuery', () => { }) ).toEqual({ index, - body: { - query: { - bool: { - filter: [ - { - bool: { - should: [ - { - match: { - 'signal.rule.rule_id': ruleId, - }, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { + match: { + 'signal.rule.rule_id': ruleId, }, - { - match: { - [ALERT_RULE_RULE_ID]: ruleId, - }, + }, + { + match: { + [ALERT_RULE_RULE_ID]: ruleId, }, - ], - minimum_should_match: 1, - }, - }, - { - range: { - '@timestamp': { - gt: from, - lte: to, - format: 'epoch_millis', }, + ], + minimum_should_match: 1, + }, + }, + { + range: { + '@timestamp': { + gt: from, + lte: to, + format: 'epoch_millis', }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.ts index 9455f40aa83ed..184d24a2927f1 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/build_signals_query.ts @@ -21,39 +21,37 @@ export const buildSignalsSearchQuery = ({ size, }: BuildSignalsSearchQuery) => ({ index, - body: { - size, - query: { - bool: { - filter: [ - { - bool: { - should: [ - { - match: { - 'signal.rule.rule_id': ruleId, - }, + size, + query: { + bool: { + filter: [ + { + bool: { + should: [ + { + match: { + 'signal.rule.rule_id': ruleId, }, - { - match: { - 'kibana.alert.rule.rule_id': ruleId, - }, + }, + { + match: { + 'kibana.alert.rule.rule_id': ruleId, }, - ], - minimum_should_match: 1, - }, - }, - { - range: { - '@timestamp': { - gt: from, - lte: to, - format: 'epoch_millis', }, + ], + minimum_should_match: 1, + }, + }, + { + range: { + '@timestamp': { + gt: from, + lte: to, + format: 'epoch_millis', }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/utils.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/utils.test.ts index a25141635b518..849bccd05e38c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/utils.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/utils.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import type { SignalSource } from '../../../rule_types/types'; import { deconflictSignalsAndResults, getNotificationResultsLink } from './utils'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/health_stats_for_rule.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/health_stats_for_rule.ts index 28e1d4ee838d7..6e9f47bb8875b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/health_stats_for_rule.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/health_stats_for_rule.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { AggregateEventsBySavedObjectResult } from '@kbn/event-log-plugin/server'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/rule_execution_stats.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/rule_execution_stats.ts index 141831b98263a..a08de70c44861 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/rule_execution_stats.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/aggregations/rule_execution_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { mapValues } from 'lodash'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/event_log_health_client.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/event_log_health_client.ts index 851f16f21d911..551f1660adedf 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/event_log_health_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/event_log/event_log_health_client.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { Logger } from '@kbn/core/server'; import { SavedObjectsUtils } from '@kbn/core/server'; import type { KueryNode } from '@kbn/es-query'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_cluster.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_cluster.ts index 3ceecf16da15b..c79fec1931728 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_cluster.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_cluster.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { ClusterHealthState } from '../../../../../../../../common/api/detection_engine/rule_monitoring'; import { getRuleStatsAggregation, normalizeRuleStatsAggregation } from './rule_stats'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_space.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_space.ts index 8548baef05f31..2688d6a60c4e8 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_space.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/health_stats_for_space.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SpaceHealthState } from '../../../../../../../../common/api/detection_engine/rule_monitoring'; import { getRuleStatsAggregation, normalizeRuleStatsAggregation } from './rule_stats'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/rule_stats.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/rule_stats.ts index 8d616d8fc677c..0d4db77eda6ec 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/rule_stats.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_objects/aggregations/rule_stats.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { HealthOverviewState, TotalEnabledDisabled, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_spaces/aggregations/spaces.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_spaces/aggregations/spaces.ts index c95ce108afe38..b48d9efc13d7b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_spaces/aggregations/spaces.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/detection_engine_health/rule_spaces/aggregations/spaces.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { RawData } from '../../../utils/normalization'; // The number of Kibana spaces is limited by the `maxSpaces` config setting of the spaces plugin. diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts index 6d35b25110d6a..48fc86da6cd93 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { AggregateEventsBySavedObjectResult } from '@kbn/event-log-plugin/server'; import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { MAX_EXECUTION_EVENTS_DISPLAYED } from '@kbn/securitysolution-rules'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/types.ts index 70ab3e746e961..a834b308007e4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { RuleRunType } from '../../../../../../../../../common/api/detection_engine/rule_monitoring'; type AlertCounts = estypes.AggregationsMultiBucketAggregateBase & { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/event_log_reader.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/event_log_reader.ts index c61e696e30673..ba877fa9ec091 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/event_log_reader.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/event_log_reader.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { IEventLogClient, IValidatedEvent } from '@kbn/event-log-plugin/server'; import { MAX_EXECUTION_EVENTS_DISPLAYED } from '@kbn/securitysolution-rules'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.test.ts index d35f63d35fd7e..db481285ca9c3 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.test.ts @@ -10,7 +10,7 @@ import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { wrapScopedClusterClient } from './wrap_scoped_cluster_client'; const esQuery = { - body: { query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } } }, + query: { bool: { filter: { range: { '@timestamp': { gte: 0 } } } } }, }; describe('wrapScopedClusterClient', () => { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.ts index 2327ea438189f..c348f64ef60fe 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/wrap_scoped_cluster_client.ts @@ -15,11 +15,8 @@ import type { SearchRequest, SearchResponse, AggregateName, -} from '@elastic/elasticsearch/lib/api/types'; -import type { - SearchRequest as SearchRequestWithBody, AggregationsAggregate, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { IScopedClusterClient, ElasticsearchClient } from '@kbn/core/server'; interface WrapScopedClusterClientOpts { @@ -93,28 +90,28 @@ function getWrappedSearchFn(opts: WrapEsClientOpts) { TDocument = unknown, TAggregations = Record >( - params?: SearchRequest | SearchRequestWithBody, + params?: SearchRequest, options?: TransportRequestOptionsWithOutMeta ): Promise>; async function search< TDocument = unknown, TAggregations = Record >( - params?: SearchRequest | SearchRequestWithBody, + params?: SearchRequest, options?: TransportRequestOptionsWithMeta ): Promise, unknown>>; async function search< TDocument = unknown, TAggregations = Record >( - params?: SearchRequest | SearchRequestWithBody, + params?: SearchRequest, options?: TransportRequestOptions ): Promise>; async function search< TDocument = unknown, TAggregations = Record >( - params?: SearchRequest | SearchRequestWithBody, + params?: SearchRequest, options?: TransportRequestOptions ): Promise< | TransportResult, unknown> diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts index f733cd2a07c9c..675e2428622bd 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/create_security_rule_type_wrapper.ts @@ -8,7 +8,7 @@ import { isEmpty, partition } from 'lodash'; import agent from 'elastic-apm-node'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { IndexPatternsFetcher } from '@kbn/data-plugin/server'; import { TIMESTAMP } from '@kbn/rule-data-utils'; import { createPersistenceRuleTypeWrapper } from '@kbn/rule-registry-plugin/server'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.test.ts index 8a7edc88eb784..aafa5882a4c69 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.test.ts @@ -37,38 +37,36 @@ describe('buildEqlSearchRequest', () => { expect(request).toEqual({ allow_no_indices: true, index: ['testindex1', 'testindex2'], - body: { - size: 100, - query: 'process where true', - runtime_mappings: undefined, - filter: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'now', - format: 'strict_date_optional_time', - }, + size: 100, + query: 'process where true', + runtime_mappings: undefined, + filter: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'now', + format: 'strict_date_optional_time', }, }, - emptyFilter, - ], - }, + }, + emptyFilter, + ], }, - allow_partial_search_results: true, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], }, + allow_partial_search_results: true, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }); }); @@ -90,74 +88,72 @@ describe('buildEqlSearchRequest', () => { expect(request).toEqual({ allow_no_indices: true, index: ['testindex1', 'testindex2'], - body: { - event_category_field: 'event.other_category', - size: 100, - query: 'process where true', - runtime_mappings: undefined, - filter: { - bool: { - filter: [ - { - bool: { - minimum_should_match: 1, - should: [ - { - range: { - 'event.ingested': { - lte: 'now', - gte: 'now-5m', - format: 'strict_date_optional_time', - }, + event_category_field: 'event.other_category', + size: 100, + query: 'process where true', + runtime_mappings: undefined, + filter: { + bool: { + filter: [ + { + bool: { + minimum_should_match: 1, + should: [ + { + range: { + 'event.ingested': { + lte: 'now', + gte: 'now-5m', + format: 'strict_date_optional_time', }, }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - lte: 'now', - gte: 'now-5m', - format: 'strict_date_optional_time', - }, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + lte: 'now', + gte: 'now-5m', + format: 'strict_date_optional_time', }, }, - { - bool: { - must_not: { - exists: { - field: 'event.ingested', - }, + }, + { + bool: { + must_not: { + exists: { + field: 'event.ingested', }, }, }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - emptyFilter, - ], - }, + }, + emptyFilter, + ], }, - allow_partial_search_results: true, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: 'event.ingested', - format: 'strict_date_optional_time', - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], }, + allow_partial_search_results: true, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: 'event.ingested', + format: 'strict_date_optional_time', + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }); }); @@ -179,39 +175,37 @@ describe('buildEqlSearchRequest', () => { expect(request).toEqual({ allow_no_indices: true, index: ['testindex1', 'testindex2'], - body: { - event_category_field: 'event.other_category', - size: 100, - query: 'process where true', - runtime_mappings: undefined, - filter: { - bool: { - filter: [ - { - range: { - 'event.ingested': { - lte: 'now', - gte: 'now-5m', - format: 'strict_date_optional_time', - }, + event_category_field: 'event.other_category', + size: 100, + query: 'process where true', + runtime_mappings: undefined, + filter: { + bool: { + filter: [ + { + range: { + 'event.ingested': { + lte: 'now', + gte: 'now-5m', + format: 'strict_date_optional_time', }, }, - emptyFilter, - ], - }, + }, + emptyFilter, + ], }, - allow_partial_search_results: true, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: 'event.ingested', - format: 'strict_date_optional_time', - }, - ], }, + allow_partial_search_results: true, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: 'event.ingested', + format: 'strict_date_optional_time', + }, + ], }); }); @@ -240,94 +234,92 @@ describe('buildEqlSearchRequest', () => { expect(request).toMatchInlineSnapshot(` Object { "allow_no_indices": true, - "body": Object { - "allow_partial_search_results": true, - "event_category_field": undefined, - "fields": Array [ - Object { - "field": "*", - "include_unmapped": true, - }, - Object { - "field": "@timestamp", - "format": "strict_date_optional_time", - }, - ], - "filter": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "strict_date_optional_time", - "gte": "now-5m", - "lte": "now", - }, + "allow_partial_search_results": true, + "event_category_field": undefined, + "fields": Array [ + Object { + "field": "*", + "include_unmapped": true, + }, + Object { + "field": "@timestamp", + "format": "strict_date_optional_time", + }, + ], + "filter": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "strict_date_optional_time", + "gte": "now-5m", + "lte": "now", }, }, - Object { - "bool": Object { - "filter": Array [], - "must": Array [], - "must_not": Array [ - Object { - "bool": Object { - "should": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "nested": Object { - "path": "some.parentField", - "query": Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "some.parentField.nested.field": "some value", - }, + }, + Object { + "bool": Object { + "filter": Array [], + "must": Array [], + "must_not": Array [ + Object { + "bool": Object { + "should": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "nested": Object { + "path": "some.parentField", + "query": Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "some.parentField.nested.field": "some value", }, - ], - }, + }, + ], }, - "score_mode": "none", }, + "score_mode": "none", }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "match_phrase": Object { - "some.not.nested.field": "some value", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "match_phrase": Object { + "some.not.nested.field": "some value", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - ], - "should": Array [], - }, + }, + ], + "should": Array [], }, - ], - }, + }, + ], }, - "query": "process where true", - "runtime_mappings": undefined, - "size": 100, - "timestamp_field": undefined, }, "index": Array [ "testindex1", "testindex2", ], + "query": "process where true", + "runtime_mappings": undefined, + "size": 100, + "timestamp_field": undefined, } `); }); @@ -382,55 +374,53 @@ describe('buildEqlSearchRequest', () => { expect(request).toEqual({ allow_no_indices: true, index: ['testindex1', 'testindex2'], - body: { - size: 100, - query: 'process where true', - filter: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'now', - format: 'strict_date_optional_time', - }, + size: 100, + query: 'process where true', + filter: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'now', + format: 'strict_date_optional_time', }, }, - { - bool: { - must: [], - filter: [ - { - exists: { - field: 'process.name', - }, + }, + { + bool: { + must: [], + filter: [ + { + exists: { + field: 'process.name', }, - { - match_phrase: { - 'host.name': 'Host-b4d9hu1a56', - }, + }, + { + match_phrase: { + 'host.name': 'Host-b4d9hu1a56', }, - ], - should: [], - must_not: [], - }, + }, + ], + should: [], + must_not: [], }, - ], - }, + }, + ], }, - allow_partial_search_results: true, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], }, + allow_partial_search_results: true, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }); }); @@ -450,7 +440,7 @@ describe('buildEqlSearchRequest', () => { eventCategoryOverride: undefined, exceptionFilter: undefined, }); - expect(request?.body?.tiebreaker_field).toEqual(`host.name`); + expect(request?.tiebreaker_field).toEqual(`host.name`); }); test('should not pass a tiebreaker field with a valid value', async () => { @@ -468,7 +458,7 @@ describe('buildEqlSearchRequest', () => { eventCategoryOverride: undefined, exceptionFilter: undefined, }); - expect(request?.body?.tiebreaker_field).toEqual(undefined); + expect(request?.tiebreaker_field).toEqual(undefined); }); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.ts index 0e855befb3f8a..1face86c62c91 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/build_eql_search_request.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Filter } from '@kbn/es-query'; import { isEmpty } from 'lodash/fp'; import type { @@ -79,29 +79,25 @@ export const buildEqlSearchRequest = ({ return { index, allow_no_indices: true, - body: { - size, - query, - filter: { - bool: { - filter: requestFilter, - }, + size, + query, + filter: { + bool: { + filter: requestFilter, }, - // the allow_partial_search_results query parameter will supersede - // the corresponding xpack settings on cluster - // @ts-expect-error unknown property allow_partial_search_results - // TODO: remove this ts-expect when 8.18 elasticsearch client is released. - // issue: https://github.com/elastic/kibana/issues/208760 - allow_partial_search_results: true, - runtime_mappings: runtimeMappings, - timestamp_field: timestampField, - event_category_field: eventCategoryOverride, - ...(!isEmpty(tiebreakerField) - ? { - tiebreaker_field: tiebreakerField, - } - : {}), - fields, }, + // the allow_partial_search_results query parameter will supersede + // the corresponding xpack settings on cluster + // issue: https://github.com/elastic/kibana/issues/208760 + allow_partial_search_results: true, + runtime_mappings: runtimeMappings, + timestamp_field: timestampField, + event_category_field: eventCategoryOverride, + ...(!isEmpty(tiebreakerField) + ? { + tiebreaker_field: tiebreakerField, + } + : {}), + fields, }; }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.test.ts index f1fabcfd0f96b..ba81261cff8ec 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.test.ts @@ -201,7 +201,7 @@ describe('eql_executor', () => { alertServices.scopedClusterClient.asCurrentUser.eql.search.mock.calls[0][0]; expect(searchArgs).toHaveProperty( - 'body.filter.bool.filter', + 'filter.bool.filter', expect.arrayContaining([ { bool: { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.ts index de3972abf2ae9..423cc04375d24 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/eql/eql.ts @@ -13,10 +13,11 @@ import type { AlertInstanceState, RuleExecutorServices, } from '@kbn/alerting-plugin/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Filter } from '@kbn/es-query'; import isEmpty from 'lodash/isEmpty'; +import type { ShardFailure } from '@elastic/elasticsearch/lib/api/types'; import { buildEqlSearchRequest } from './build_eql_search_request'; import { createEnrichEventsFunction } from '../utils/enrichments'; @@ -171,14 +172,14 @@ export const eqlExecutor = async ({ let newSignals: Array> | undefined; - // @ts-expect-error shard_failures exists in - // elasticsearch response v9 - // needs to be spec needs to be backported - // https://github.com/elastic/elasticsearch-specification/pull/3372#issuecomment-2621835599 - // TODO: remove ts-expect-error when ES lib version is updated const shardFailures = response.shard_failures; if (!isEmpty(shardFailures)) { - logShardFailures(isSequenceQuery, shardFailures, result, ruleExecutionLogger); + logShardFailures( + isSequenceQuery, + shardFailures as ShardFailure[], + result, + ruleExecutionLogger + ); } const { events, sequences } = response.hits; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/build_esql_search_request.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/build_esql_search_request.ts index 54ddd9b818c23..a47512b9c9b00 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/build_esql_search_request.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/build_esql_search_request.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Filter } from '@kbn/es-query'; import type { RuleFilterArray, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/esql.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/esql.ts index 2c1aacd79bc48..f6919b0d301f4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/esql.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/esql.ts @@ -11,7 +11,7 @@ import type { AlertInstanceState, RuleExecutorServices, } from '@kbn/alerting-plugin/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { computeIsESQLQueryAggregating, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/fetch_source_documents.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/fetch_source_documents.ts index 16596a6d78650..e9b73b3b9bac3 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/fetch_source_documents.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/fetch_source_documents.ts @@ -6,7 +6,7 @@ */ import type { ElasticsearchClient } from '@kbn/core/server'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { RulePreviewLoggedRequest } from '../../../../../common/api/detection_engine/rule_preview/rule_preview.gen'; import { logQueryRequest } from '../utils/logged_requests'; import * as i18n from '../translations'; @@ -76,7 +76,7 @@ export const fetchSourceDocuments = async ({ const response = await esClient.search({ index, - body: searchBody, + ...searchBody, ignore_unavailable: ignoreUnavailable, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.test.ts index d16e1fa405882..64cfa419df9b0 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.test.ts @@ -6,7 +6,7 @@ */ import { generateAlertId } from './generate_alert_id'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SignalSource } from '../../types'; import type { CompleteRule, EsqlRuleParams } from '../../../rule_schema'; import moment from 'moment'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.ts index b064079c743fd..e2ab5020113b0 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/utils/generate_alert_id.ts @@ -7,7 +7,7 @@ import objectHash from 'object-hash'; import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { CompleteRule, EsqlRuleParams } from '../../../rule_schema'; import type { SignalSource } from '../../types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_esql_alerts.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_esql_alerts.ts index 917635c26b6ac..34c6dd6821a75 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_esql_alerts.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_esql_alerts.ts @@ -6,7 +6,7 @@ */ import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { BaseFieldsLatest, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_suppressed_esql_alerts.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_suppressed_esql_alerts.ts index fe72aa566583a..79ab73ccbf4fe 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_suppressed_esql_alerts.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/esql/wrap_suppressed_esql_alerts.ts @@ -7,7 +7,7 @@ import objectHash from 'object-hash'; import type { Moment } from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { TIMESTAMP } from '@kbn/rule-data-utils'; import type { SuppressionFieldsLatest } from '@kbn/rule-registry-plugin/common/schemas'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/utils/transform_hit_to_alert.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/utils/transform_hit_to_alert.ts index b95d335642b2f..fb2e95a41a46c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/utils/transform_hit_to_alert.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/utils/transform_hit_to_alert.ts @@ -6,7 +6,7 @@ */ import { merge } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { requiredOptional } from '@kbn/zod-helpers'; import { EVENT_KIND } from '@kbn/rule-data-utils'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/wrap_hits_factory.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/wrap_hits_factory.ts index cdcf9e0716ec5..dcd2c7be1e9da 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/wrap_hits_factory.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/factories/wrap_hits_factory.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ConfigType } from '../../../../config'; import type { SignalSource, SimpleHit } from '../types'; import type { CompleteRule, RuleParams } from '../../rule_schema'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/indicator_match.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/indicator_match.ts index d243943b9417c..e528ed96f0f35 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/indicator_match.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/indicator_match.ts @@ -6,7 +6,7 @@ */ import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { LicensingPluginSetup } from '@kbn/licensing-plugin/server'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/build_threat_mapping_filter.mock.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/build_threat_mapping_filter.mock.ts index 0f4c2ed863141..802ea62895bfe 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/build_threat_mapping_filter.mock.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/build_threat_mapping_filter.mock.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ThreatMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import type { Filter } from '@kbn/es-query'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/create_threat_signals.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/create_threat_signals.ts index 6c65d3934eeff..f1d69f49d351b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/create_threat_signals.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/create_threat_signals.ts @@ -7,7 +7,7 @@ import { firstValueFrom } from 'rxjs'; -import type { OpenPointInTimeResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { OpenPointInTimeResponse } from '@elastic/elasticsearch/lib/api/types'; import { uniq, chunk } from 'lodash/fp'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.test.ts index 13cf5a21b2a3d..edf174906e34d 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.test.ts @@ -29,22 +29,20 @@ describe('getEventCount', () => { }); expect(esClient.count).toHaveBeenCalledWith({ - body: { - query: { - bool: { - filter: [ - { bool: { must: [], filter: [], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - lte: '2022-01-14T05:00:00.000Z', - gte: '2022-01-13T05:00:00.000Z', - format: 'strict_date_optional_time', - }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + lte: '2022-01-14T05:00:00.000Z', + gte: '2022-01-13T05:00:00.000Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, }, ignore_unavailable: true, @@ -67,45 +65,43 @@ describe('getEventCount', () => { }); expect(esClient.count).toHaveBeenCalledWith({ - body: { - query: { - bool: { - filter: [ - { bool: { must: [], filter: [], should: [], must_not: [] } }, - { - bool: { - should: [ - { - range: { - 'event.ingested': { - lte: '2022-01-14T05:00:00.000Z', - gte: '2022-01-13T05:00:00.000Z', - format: 'strict_date_optional_time', - }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [], should: [], must_not: [] } }, + { + bool: { + should: [ + { + range: { + 'event.ingested': { + lte: '2022-01-14T05:00:00.000Z', + gte: '2022-01-13T05:00:00.000Z', + format: 'strict_date_optional_time', }, }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - lte: '2022-01-14T05:00:00.000Z', - gte: '2022-01-13T05:00:00.000Z', - format: 'strict_date_optional_time', - }, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + lte: '2022-01-14T05:00:00.000Z', + gte: '2022-01-13T05:00:00.000Z', + format: 'strict_date_optional_time', }, }, - { bool: { must_not: { exists: { field: 'event.ingested' } } } }, - ], - }, + }, + { bool: { must_not: { exists: { field: 'event.ingested' } } } }, + ], }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - ], - }, + }, + ], }, }, ignore_unavailable: true, @@ -127,22 +123,20 @@ describe('getEventCount', () => { }); expect(esClient.count).toHaveBeenCalledWith({ - body: { - query: { - bool: { - filter: [ - { bool: { must: [], filter: [], should: [], must_not: [] } }, - { - range: { - 'event.ingested': { - lte: '2022-01-14T05:00:00.000Z', - gte: '2022-01-13T05:00:00.000Z', - format: 'strict_date_optional_time', - }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [], should: [], must_not: [] } }, + { + range: { + 'event.ingested': { + lte: '2022-01-14T05:00:00.000Z', + gte: '2022-01-13T05:00:00.000Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, }, ignore_unavailable: true, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.ts index 0f631542679bd..ac5c7a9bcde35 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_event_count.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { EventCountOptions, EventsOptions, EventDoc } from './types'; import { getQueryFilter } from '../../utils/get_query_filter'; import { singleSearchAfter } from '../../utils/single_search_after'; @@ -100,9 +100,9 @@ export const getEventCount = async ({ secondaryTimestamp, searchAfterSortIds: undefined, runtimeMappings: undefined, - }).body?.query; + }).query; const response = await esClient.count({ - body: { query: eventSearchQueryBodyQuery }, + query: eventSearchQueryBodyQuery, ignore_unavailable: true, index, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_threat_list.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_threat_list.ts index 9009d20c379df..7e3478b7edd07 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_threat_list.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/get_threat_list.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { getQueryFilter } from '../../utils/get_query_filter'; import type { GetThreatListOptions, @@ -57,16 +57,14 @@ export const getThreatList = async ({ ThreatListDoc, Record >({ - body: { - ...threatListConfig, - query: queryFilter, - search_after: searchAfter, - runtime_mappings: runtimeMappings, - sort: getSortForThreatList({ - index, - listItemIndex: listClient.getListItemName(), - }), - }, + ...threatListConfig, + query: queryFilter, + search_after: searchAfter, + runtime_mappings: runtimeMappings, + sort: getSortForThreatList({ + index, + listItemIndex: listClient.getListItemName(), + }), track_total_hits: false, size: calculatedPerPage, pit: { id: pitId }, @@ -109,9 +107,7 @@ export const getThreatListCount = async ({ fields: indexFields, }); const response = await esClient.count({ - body: { - query: queryFilter, - }, + query: queryFilter, ignore_unavailable: true, index, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/types.ts index 4eac8bd6a8864..87e9b1d7891b7 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/threat_mapping/types.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ThreatQuery, ThreatMapping, @@ -18,9 +18,11 @@ import type { Type, } from '@kbn/securitysolution-io-ts-alerting-types'; import type { LicensingPluginSetup } from '@kbn/licensing-plugin/server'; -import type { QueryDslBoolQuery } from '@elastic/elasticsearch/lib/api/types'; +import type { + OpenPointInTimeResponse, + QueryDslBoolQuery, +} from '@elastic/elasticsearch/lib/api/types'; import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import type { OpenPointInTimeResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ListClient } from '@kbn/lists-plugin/server'; import type { AlertInstanceContext, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/ml/bulk_create_ml_signals.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/ml/bulk_create_ml_signals.ts index 11343645f8ff4..24dc3c7016364 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/ml/bulk_create_ml_signals.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/ml/bulk_create_ml_signals.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { flow, omit } from 'lodash/fp'; import set from 'set-value'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/build_new_terms_aggregation.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/build_new_terms_aggregation.ts index d628d8dbf2d90..6df36881cd7de 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/build_new_terms_aggregation.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/build_new_terms_aggregation.ts @@ -13,27 +13,27 @@ import type { NewTermsFieldsLatest } from '../../../../../common/api/detection_e export type RecentTermsAggResult = ESSearchResponse< SignalSource, - { body: { aggregations: ReturnType } } + { aggregations: ReturnType } >; export type NewTermsAggResult = ESSearchResponse< SignalSource, - { body: { aggregations: ReturnType } } + { aggregations: ReturnType } >; export type CompositeDocFetchAggResult = ESSearchResponse< SignalSource, - { body: { aggregations: ReturnType } } + { aggregations: ReturnType } >; export type CompositeNewTermsAggResult = ESSearchResponse< SignalSource, - { body: { aggregations: ReturnType } } + { aggregations: ReturnType } >; export type DocFetchAggResult = ESSearchResponse< SignalSource, - { body: { aggregations: ReturnType } } + { aggregations: ReturnType } >; export type CreateAlertsHook = ( diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/types.ts index 270ffefb6b448..cd31024d9fa46 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import type { SignalSource } from '../types'; export interface EventsAndTerms { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts index 30faf1f64fa96..e2b9023f49906 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts @@ -7,7 +7,7 @@ import dateMath from '@elastic/datemath'; import moment from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export const parseDateString = ({ date, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_new_terms_alerts.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_new_terms_alerts.ts index 666062592237c..ae6e4d5a89a14 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_new_terms_alerts.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_new_terms_alerts.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import objectHash from 'object-hash'; import type { BaseFieldsLatest, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_suppressed_new_terms_alerts.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_suppressed_new_terms_alerts.ts index dc9a322301126..72d45521a7d95 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_suppressed_new_terms_alerts.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/wrap_suppressed_new_terms_alerts.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import objectHash from 'object-hash'; import { TIMESTAMP } from '@kbn/rule-data-utils'; import type { SuppressionFieldsLatest } from '@kbn/rule-registry-plugin/common/schemas'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/build_group_by_field_aggregation.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/build_group_by_field_aggregation.ts index bf73c13f7bc79..9ef377db698d4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/build_group_by_field_aggregation.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/build_group_by_field_aggregation.ts @@ -11,9 +11,7 @@ import type { SignalSource } from '../../types'; export type EventGroupingMultiBucketAggregationResult = ESSearchResponse< SignalSource, { - body: { - aggregations: ReturnType; - }; + aggregations: ReturnType; } >; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/group_and_bulk_create.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/group_and_bulk_create.ts index 12a8e0d41fb9f..654966fb94786 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/group_and_bulk_create.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/group_and_bulk_create.ts @@ -7,7 +7,7 @@ import type moment from 'moment'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { withSecuritySpan } from '../../../../../utils/with_security_span'; import { buildTimeRangeFilter } from '../../utils/build_events_query'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/wrap_suppressed_alerts.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/wrap_suppressed_alerts.ts index 6961c3bcef15e..a21ba37397365 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/wrap_suppressed_alerts.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/query/alert_suppression/wrap_suppressed_alerts.ts @@ -6,7 +6,7 @@ */ import objectHash from 'object-hash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ALERT_SUPPRESSION_TERMS, ALERT_SUPPRESSION_DOCS_COUNT, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/__snapshots__/get_threshold_signal_history.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/__snapshots__/get_threshold_signal_history.test.ts.snap index bb9e29f1f5b52..3a4a246e7f768 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/__snapshots__/get_threshold_signal_history.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/__snapshots__/get_threshold_signal_history.test.ts.snap @@ -2,114 +2,110 @@ exports[`buildPreviousThresholdAlertRequest should generate a proper request when bucketByFields contains multiple fields 1`] = ` Object { - "body": Object { - "query": Object { - "bool": Object { - "must": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "strict_date_optional_time", - "gte": "now-6m", - "lte": "now", - }, + "query": Object { + "bool": Object { + "must": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "strict_date_optional_time", + "gte": "now-6m", + "lte": "now", }, }, - Object { - "term": Object { - "kibana.alert.rule.uuid": "threshold-rule", - }, + }, + Object { + "term": Object { + "kibana.alert.rule.uuid": "threshold-rule", }, - Object { - "range": Object { - "signal.original_time": Object { - "gte": "now-6m", - }, + }, + Object { + "range": Object { + "signal.original_time": Object { + "gte": "now-6m", }, }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "term": Object { - "signal.rule.threshold.field": "host.name", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "term": Object { + "signal.rule.threshold.field": "host.name", }, - Object { - "term": Object { - "kibana.alert.rule.parameters.threshold.field": "host.name", - }, + }, + Object { + "term": Object { + "kibana.alert.rule.parameters.threshold.field": "host.name", }, - ], - }, + }, + ], }, - Object { - "bool": Object { - "minimum_should_match": 1, - "should": Array [ - Object { - "term": Object { - "signal.rule.threshold.field": "user.name", - }, + }, + Object { + "bool": Object { + "minimum_should_match": 1, + "should": Array [ + Object { + "term": Object { + "signal.rule.threshold.field": "user.name", }, - Object { - "term": Object { - "kibana.alert.rule.parameters.threshold.field": "user.name", - }, + }, + Object { + "term": Object { + "kibana.alert.rule.parameters.threshold.field": "user.name", }, - ], - }, + }, + ], }, - ], - }, + }, + ], }, - "size": 10000, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], }, + "size": 10000, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], } `; exports[`buildPreviousThresholdAlertRequest should generate a proper request when bucketByFields is empty 1`] = ` Object { - "body": Object { - "query": Object { - "bool": Object { - "must": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "strict_date_optional_time", - "gte": "now-6m", - "lte": "now", - }, + "query": Object { + "bool": Object { + "must": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "strict_date_optional_time", + "gte": "now-6m", + "lte": "now", }, }, - Object { - "term": Object { - "kibana.alert.rule.uuid": "threshold-rule", - }, + }, + Object { + "term": Object { + "kibana.alert.rule.uuid": "threshold-rule", }, - Object { - "range": Object { - "signal.original_time": Object { - "gte": "now-6m", - }, + }, + Object { + "range": Object { + "signal.original_time": Object { + "gte": "now-6m", }, }, - ], - }, + }, + ], }, - "size": 10000, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], }, + "size": 10000, + "sort": Array [ + Object { + "@timestamp": "desc", + }, + ], } `; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/build_signal_history.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/build_signal_history.ts index e6390fe7f67ea..d70cd16c829fd 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/build_signal_history.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/build_signal_history.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { ALERT_RULE_PARAMETERS } from '@kbn/rule-data-utils'; import { ALERT_ORIGINAL_TIME } from '../../../../../common/field_maps/field_names'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/bulk_create_suppressed_threshold_alerts.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/bulk_create_suppressed_threshold_alerts.ts index d3b5f3fb88fa8..ed8e06cd6a1e1 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/bulk_create_suppressed_threshold_alerts.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/bulk_create_suppressed_threshold_alerts.ts @@ -11,7 +11,7 @@ import type { RuleExecutorServices, } from '@kbn/alerting-plugin/server'; import type { SuppressionFieldsLatest } from '@kbn/rule-registry-plugin/common/schemas'; -import type { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { buildReasonMessageForThresholdAlert } from '../utils/reason_formatters'; import type { ThresholdBucket } from './types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/find_threshold_signals.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/find_threshold_signals.ts index f14f22acf0a0d..9d6320d95fef7 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/find_threshold_signals.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/find_threshold_signals.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isEmpty } from 'lodash'; import type { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_signal_history.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_signal_history.ts index e82e33c9e6e95..ff690eaff175a 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_signal_history.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_signal_history.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { IRuleDataClient } from '@kbn/rule-registry-plugin/server'; import { ALERT_RULE_UUID } from '@kbn/rule-data-utils'; import type { ElasticsearchClient } from '@kbn/core/server'; @@ -70,61 +70,57 @@ export const buildPreviousThresholdAlertRequest = ({ bucketByFields: string[]; }): estypes.SearchRequest => { return { - // We should switch over to @elastic/elasticsearch/lib/api/types instead of typesWithBodyKey where possible, - // but api/types doesn't have a complete type for `sort` - body: { - size: 10000, - sort: [ - { - '@timestamp': 'desc', - }, - ], - query: { - bool: { - must: [ - { - range: { - '@timestamp': { - lte: to, - gte: from, - format: 'strict_date_optional_time', - }, + size: 10000, + sort: [ + { + '@timestamp': 'desc', + }, + ], + query: { + bool: { + must: [ + { + range: { + '@timestamp': { + lte: to, + gte: from, + format: 'strict_date_optional_time', }, }, - { - term: { - [ALERT_RULE_UUID]: frameworkRuleId, - }, + }, + { + term: { + [ALERT_RULE_UUID]: frameworkRuleId, }, - // We might find a signal that was generated on the interval for old data... make sure to exclude those. - { - range: { - 'signal.original_time': { - gte: from, - }, + }, + // We might find a signal that was generated on the interval for old data... make sure to exclude those. + { + range: { + 'signal.original_time': { + gte: from, }, }, - ...bucketByFields.map((field) => { - return { - bool: { - should: [ - { - term: { - 'signal.rule.threshold.field': field, - }, + }, + ...bucketByFields.map((field) => { + return { + bool: { + should: [ + { + term: { + 'signal.rule.threshold.field': field, }, - { - term: { - 'kibana.alert.rule.parameters.threshold.field': field, - }, + }, + { + term: { + 'kibana.alert.rule.parameters.threshold.field': field, }, - ], - minimum_should_match: 1, - }, - }; - }), - ], - }, + }, + ], + minimum_should_match: 1, + }, + }; + }), + ], }, }, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/threshold.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/threshold.ts index f3640b0ea84da..aaec187605cf1 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/threshold.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/threshold.ts @@ -8,7 +8,7 @@ import { isEmpty } from 'lodash'; import { firstValueFrom } from 'rxjs'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; import type { LicensingPluginSetup } from '@kbn/licensing-plugin/server'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/types.ts index 14e244000a30d..1f79a5c505078 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/types.ts @@ -10,7 +10,7 @@ import type { AggregationsCompositeBucket, AggregationsMaxAggregate, AggregationsMinAggregate, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; import type { ESSearchResponse } from '@kbn/es-types'; import type { RuleTypeState } from '@kbn/alerting-plugin/server'; import type { SignalSource } from '../types'; @@ -29,18 +29,14 @@ export interface ThresholdLeafAggregates { export type ThresholdMultiBucketAggregationResult = ESSearchResponse< SignalSource, { - body: { - aggregations: ReturnType; - }; + aggregations: ReturnType; } >; export type ThresholdSingleBucketAggregationResult = ESSearchResponse< SignalSource, { - body: { - aggregations: ReturnType; - }; + aggregations: ReturnType; } >; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts index 27b14db5c1bb4..0e3269118d3af 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/types.ts @@ -9,7 +9,7 @@ import type { Moment } from 'moment'; import type { Logger } from '@kbn/logging'; import type { ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { SuppressionFieldsLatest } from '@kbn/rule-registry-plugin/common/schemas'; import type { AnalyticsServiceSetup } from '@kbn/core-analytics-server'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.test.ts index 074931be1988d..ac91e20c577af 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.test.ts @@ -24,43 +24,41 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [ - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', }, - }, - ], + ], + }, }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [ + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); @@ -80,84 +78,82 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - bool: { - should: [ - { - range: { - 'event.ingested': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + bool: { + should: [ + { + range: { + 'event.ingested': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + }, + { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - { - bool: { - must_not: { - exists: { - field: 'event.ingested', - }, + }, + { + bool: { + must_not: { + exists: { + field: 'event.ingested', }, }, }, - ], - }, + }, + ], }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: 'event.ingested', - format: 'strict_date_optional_time', - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [ - { - 'event.ingested': { - order: 'asc', - unmapped_type: 'date', }, + ], + }, + }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: 'event.ingested', + format: 'strict_date_optional_time', + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [ + { + 'event.ingested': { + order: 'asc', + unmapped_type: 'date', }, - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', - }, + }, + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', }, - ], - }, + }, + ], }); }); @@ -177,43 +173,41 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - 'event.ingested': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + 'event.ingested': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: 'event.ingested', - format: 'strict_date_optional_time', - }, - ], - sort: [ - { - 'event.ingested': { - order: 'asc', - unmapped_type: 'date', }, - }, - ], + ], + }, }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: 'event.ingested', + format: 'strict_date_optional_time', + }, + ], + sort: [ + { + 'event.ingested': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); @@ -234,44 +228,42 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - search_after: [fakeSortId], - sort: [ - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', }, - }, - ], + ], + }, }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + search_after: [fakeSortId], + sort: [ + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); test('if searchAfterSortIds is a valid sortId number', () => { @@ -291,44 +283,42 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - search_after: [fakeSortIdNumber], - sort: [ - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', }, - }, - ], + ], + }, }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + search_after: [fakeSortIdNumber], + sort: [ + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); test('if aggregations is not provided it should not be included', () => { @@ -347,43 +337,41 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [ - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', }, - }, - ], + ], + }, }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [ + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); @@ -410,50 +398,48 @@ describe('create_signals', () => { allow_no_indices: true, index: ['auditbeat-*'], ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - aggregations: { - tags: { - terms: { - field: 'tag', }, - }, + ], }, - sort: [ - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', - }, + }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + aggregations: { + tags: { + terms: { + field: 'tag', }, - ], + }, }, + sort: [ + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); @@ -470,7 +456,7 @@ describe('create_signals', () => { trackTotalHits: false, runtimeMappings: undefined, }); - expect(query.body?.track_total_hits).toEqual(false); + expect(query.track_total_hits).toEqual(false); }); test('if sortOrder is provided it should be included', () => { @@ -487,7 +473,7 @@ describe('create_signals', () => { trackTotalHits: false, runtimeMappings: undefined, }); - expect(query?.body?.sort).toEqual([ + expect(query?.sort).toEqual([ { '@timestamp': { order: 'desc', @@ -510,7 +496,7 @@ describe('create_signals', () => { sortOrder: 'desc', runtimeMappings: undefined, }); - expect(query?.body?.sort).toEqual([ + expect(query?.sort).toEqual([ { 'event.ingested': { order: 'desc', @@ -548,36 +534,33 @@ describe('create_signals', () => { runtime_mappings: undefined, track_total_hits: undefined, ignore_unavailable: true, - body: { - size: 100, - query: { - bool: { - filter: [ - {}, - { - range: { - '@timestamp': { - gte: 'now-5m', - lte: 'today', - format: 'strict_date_optional_time', - }, + size: 100, + query: { + bool: { + filter: [ + {}, + { + range: { + '@timestamp': { + gte: 'now-5m', + lte: 'today', + format: 'strict_date_optional_time', }, }, - ], - }, - }, - _source: false, - fields: ['@timestamp'], - runtime_mappings: undefined, - sort: [ - { - '@timestamp': { - order: 'asc', - unmapped_type: 'date', }, - }, - ], + ], + }, }, + _source: false, + fields: ['@timestamp'], + sort: [ + { + '@timestamp': { + order: 'asc', + unmapped_type: 'date', + }, + }, + ], }); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.ts index 67fb75eef50c4..5bdf1dddf76cb 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_events_query.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { isEmpty } from 'lodash'; import type { OverrideBodyQuery } from '../types'; import type { TimestampOverride } from '../../../../../common/api/detection_engine/model/rule_schema'; @@ -156,35 +156,30 @@ export const buildEventsSearchQuery = ({ allow_no_indices: true, index, ignore_unavailable: true, - body: { - track_total_hits: trackTotalHits, - size, - query: { - bool: { - filter: filterWithTime, - }, + track_total_hits: trackTotalHits, + size, + query: { + bool: { + filter: filterWithTime, }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - ...docFields, - ], - ...(aggregations ? { aggregations } : {}), - runtime_mappings: runtimeMappings, - sort, - ...overrideBody, }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + ...docFields, + ], + ...(aggregations ? { aggregations } : {}), + runtime_mappings: runtimeMappings, + sort, + ...overrideBody, }; if (searchAfterSortIds != null && !isEmpty(searchAfterSortIds)) { return { ...searchQuery, - body: { - ...searchQuery.body, - search_after: searchAfterSortIds, - }, + search_after: searchAfterSortIds, }; } return searchQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_timestamp_runtime_mapping.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_timestamp_runtime_mapping.ts index 3a45402b467fc..05a4ba78fa4bc 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_timestamp_runtime_mapping.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/build_timestamp_runtime_mapping.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { TIMESTAMP_RUNTIME_FIELD } from '../constants'; export const buildTimestampRuntimeMapping = ({ diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/search_enrichments.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/search_enrichments.ts index 03ccc287ddf5c..18b16a8ad0606 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/search_enrichments.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/search_enrichments.ts @@ -12,17 +12,15 @@ export const searchEnrichments: SearchEnrichments = async ({ index, services, qu try { const response = await services.scopedClusterClient.asCurrentUser.search({ index, - body: { - _source: '', - fields, - query: getQueryFilter({ - query: '', - language: 'kuery', - filters: [query], - index, - exceptionFilter: undefined, - }), - }, + _source: '', + fields, + query: getQueryFilter({ + query: '', + language: 'kuery', + filters: [query], + index, + exceptionFilter: undefined, + }), track_total_hits: false, }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/types.ts index d13d42291dc34..6ddd5fcf3c5bf 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/enrichments/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { Filter } from '@kbn/es-query'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/get_input_output_index.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/get_input_output_index.ts index 4ec860bc5ae65..cfc6b81b9663b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/get_input_output_index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/get_input_output_index.ts @@ -11,7 +11,7 @@ import type { RuleExecutorServices, } from '@kbn/alerting-plugin/server'; import type { DataViewAttributes } from '@kbn/data-views-plugin/common'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Logger } from '@kbn/core/server'; import { DEFAULT_INDEX_KEY, DEFAULT_INDEX_PATTERN } from '../../../../../common/constants'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/filter_events.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/filter_events.ts index 9f8fc026ccb6d..6c3775587f97d 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/filter_events.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/filter_events.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { partition } from 'lodash'; import type { FilterEventsOptions } from './types'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/types.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/types.ts index 859000e538fa4..e7686b9b88462 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/types.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/large_list_filters/types.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { Type, ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; import type { ListClient } from '@kbn/lists-plugin/server'; import type { IRuleExecutionLogForExecutors } from '../../../rule_monitoring'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_eql.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_eql.ts index 3f735e533b3b6..03c09b4d34b04 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_eql.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_eql.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { EqlSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { EqlSearchRequest } from '@elastic/elasticsearch/lib/api/types'; export const logEqlRequest = (request: EqlSearchRequest): string => { const allowNoIndices = diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_esql.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_esql.ts index 8b03f563597b3..6c85dacdd0d5a 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_esql.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_esql.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; export const logEsqlRequest = ( requestBody: { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_query.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_query.ts index 8ea992793e31d..f7d9b6513e4b7 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_query.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_query.ts @@ -10,7 +10,7 @@ import type { SearchSourceConfig, Indices, Fields, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +} from '@elastic/elasticsearch/lib/api/types'; interface SearchRequest { query?: QueryDslQueryContainer; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.test.ts index 9321b1f5bab7c..5deca877d4b6f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.test.ts @@ -6,7 +6,7 @@ */ import { logSearchRequest } from './log_search_request'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; describe('logSearchRequest', () => { it('should match inline snapshot when deprecated search request used', () => { @@ -74,6 +74,112 @@ describe('logSearchRequest', () => { .toMatchInlineSnapshot(` "POST /close_alerts*/_search?allow_no_indices=true&ignore_unavailable=true { + \\"index\\": [ + \\"close_alerts*\\" + ], + \\"body\\": { + \\"size\\": 0, + \\"query\\": { + \\"bool\\": { + \\"filter\\": [ + { + \\"bool\\": { + \\"must\\": [], + \\"filter\\": [ + { + \\"query_string\\": { + \\"query\\": \\"*\\" + } + }, + { + \\"bool\\": { + \\"must_not\\": [] + } + } + ], + \\"should\\": [], + \\"must_not\\": [] + } + }, + { + \\"range\\": { + \\"@timestamp\\": { + \\"lte\\": \\"2024-12-09T17:26:48.786Z\\", + \\"gte\\": \\"2013-07-14T00:26:48.786Z\\", + \\"format\\": \\"strict_date_optional_time\\" + } + } + } + ] + } + }, + \\"fields\\": [ + { + \\"field\\": \\"*\\", + \\"include_unmapped\\": true + }, + { + \\"field\\": \\"@timestamp\\", + \\"format\\": \\"strict_date_optional_time\\" + } + ], + \\"aggregations\\": { + \\"thresholdTerms\\": { + \\"composite\\": { + \\"sources\\": [ + { + \\"agent.name\\": { + \\"terms\\": { + \\"field\\": \\"agent.name\\" + } + } + }, + { + \\"destination.ip\\": { + \\"terms\\": { + \\"field\\": \\"destination.ip\\" + } + } + } + ], + \\"after\\": { + \\"agent.name\\": \\"test-6\\", + \\"destination.ip\\": \\"127.0.0.1\\" + }, + \\"size\\": 10000 + }, + \\"aggs\\": { + \\"max_timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" + } + }, + \\"min_timestamp\\": { + \\"min\\": { + \\"field\\": \\"@timestamp\\" + } + }, + \\"count_check\\": { + \\"bucket_selector\\": { + \\"buckets_path\\": { + \\"docCount\\": \\"_count\\" + }, + \\"script\\": \\"params.docCount >= 1\\" + } + } + } + } + }, + \\"runtime_mappings\\": {}, + \\"sort\\": [ + { + \\"@timestamp\\": { + \\"order\\": \\"desc\\", + \\"unmapped_type\\": \\"date\\" + } + } + ] + }, \\"size\\": 0, \\"query\\": { \\"bool\\": { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.ts index 1b0d3d9dde80b..ea0c86a1cbbd9 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/logged_requests/log_search_request.ts @@ -5,10 +5,48 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; +import { omit, pick } from 'lodash'; + +// Search body fields as per https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html#search-search-api-request-body +const BODY_FIELDS = [ + 'aggs', + 'aggregations', + 'docvalue_fields', + 'fields', + 'stored_fields', + 'explain', + 'from', + 'indices_boost', + 'knn', + 'min_score', + 'pit', + 'query', + 'retriever', + 'runtime_mappings', + 'seq_no_primary_term', + 'size', + 'sort', + '_source', + 'stats', + 'terminate_after', + 'timeout', + 'version', +]; export const logSearchRequest = (searchRequest: estypes.SearchRequest): string => { - const { body, index, ...params } = searchRequest; + const { index } = searchRequest; + + const params = { + ...omit(searchRequest, [...BODY_FIELDS, 'index', 'body', 'querystring']), + ...searchRequest.querystring, + }; + + const body = { + ...pick(searchRequest, [...BODY_FIELDS, 'index', 'body', 'querystring']), + ...(searchRequest.body as Record), + }; + const urlParams = Object.entries(params) .reduce((acc, [key, value]) => { if (value != null) { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/search_after_bulk_create_factory.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/search_after_bulk_create_factory.ts index 700799729cb3e..590496b6e1bf5 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/search_after_bulk_create_factory.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/search_after_bulk_create_factory.ts @@ -6,7 +6,7 @@ */ import { identity } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { singleSearchAfter } from './single_search_after'; import { filterEventsAgainstList } from './large_list_filters/filter_events_against_list'; import { sendAlertTelemetryEvents } from './send_telemetry_events'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.test.ts index 136951ebb0b4a..dd34e355f6995 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.test.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { sampleDocSearchResultsNoSortId, sampleDocSearchResultsWithSortId, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.ts index 96b48f385d513..b860367c242f2 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/single_search_after.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { performance } from 'perf_hooks'; import type { AlertInstanceContext, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/utils.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/utils.ts index fa7a20c8617e0..6ceefe05d566f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/utils.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/utils/utils.ts @@ -11,8 +11,7 @@ import objectHash from 'object-hash'; import dateMath from '@kbn/datemath'; import { isCCSRemoteIndexName } from '@kbn/es-query'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { TransportResult } from '@elastic/elasticsearch'; +import type { estypes, TransportResult } from '@elastic/elasticsearch'; import { ALERT_UUID, ALERT_RULE_UUID, diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts index 446d4858d4467..280430b98f267 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts @@ -236,24 +236,22 @@ describe('AssetCriticalityDataClient', () => { expect.objectContaining({ id: 'host.name:host1', index: '.asset-criticality.asset-criticality-default', - body: { - doc: { - id_field: 'host.name', - id_value: 'host1', - criticality_level: 'high_impact', - '@timestamp': expect.any(String), + doc: { + id_field: 'host.name', + id_value: 'host1', + criticality_level: 'high_impact', + '@timestamp': expect.any(String), + asset: { + criticality: 'high_impact', + }, + host: { + name: 'host1', asset: { criticality: 'high_impact', }, - host: { - name: 'host1', - asset: { - criticality: 'high_impact', - }, - }, }, - doc_as_upsert: true, }, + doc_as_upsert: true, }) ); }); @@ -271,24 +269,22 @@ describe('AssetCriticalityDataClient', () => { expect.objectContaining({ id: 'user.name:user1', index: '.asset-criticality.asset-criticality-default', - body: { - doc: { - id_field: 'user.name', - id_value: 'user1', - criticality_level: 'medium_impact', - '@timestamp': expect.any(String), + doc: { + id_field: 'user.name', + id_value: 'user1', + criticality_level: 'medium_impact', + '@timestamp': expect.any(String), + asset: { + criticality: 'medium_impact', + }, + user: { + name: 'user1', asset: { criticality: 'medium_impact', }, - user: { - name: 'user1', - asset: { - criticality: 'medium_impact', - }, - }, }, - doc_as_upsert: true, }, + doc_as_upsert: true, }) ); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.ts index 6871a3aedea41..99875df56aaf9 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.ts @@ -246,10 +246,8 @@ export class AssetCriticalityDataClient { id, index: this.getIndex(), refresh: refresh ?? false, - body: { - doc, - doc_as_upsert: true, - }, + doc, + doc_as_upsert: true, }); return doc; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.test.ts index 27c7a7b30f2c0..cd565a6f40cf7 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.test.ts @@ -98,10 +98,8 @@ describe('AssetCriticalityMigrationClient', () => { expect(esClient.updateByQuery).toHaveBeenCalledWith( expect.objectContaining({ index: assetCriticalityDataClient.getIndex(), - body: expect.objectContaining({ - query: expect.any(Object), - script: expect.any(Object), - }), + query: expect.any(Object), + script: expect.any(Object), }), expect.any(Object) ); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.ts index dc79a467f1439..85558a5c5c3d0 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_migration_client.ts @@ -79,12 +79,10 @@ export class AssetCriticalityMigrationClient { ignore_unavailable: true, allow_no_indices: true, scroll_size: 10000, - body: { - query: ECS_MAPPINGS_MIGRATION_QUERY, - script: { - source: PAINLESS_SCRIPT, - lang: 'painless', - }, + query: ECS_MAPPINGS_MIGRATION_QUERY, + script: { + source: PAINLESS_SCRIPT, + lang: 'painless', }, }, { @@ -103,20 +101,18 @@ export class AssetCriticalityMigrationClient { conflicts: 'proceed', ignore_unavailable: true, allow_no_indices: true, - body: { - query: { - bool: { - must_not: { - exists: { - field: 'event.ingested', - }, + query: { + bool: { + must_not: { + exists: { + field: 'event.ingested', }, }, }, - script: { - source: 'ctx._source.event.ingested = ctx._source.@timestamp', - lang: 'painless', - }, + }, + script: { + source: 'ctx._source.event.ingested = ctx._source.@timestamp', + lang: 'painless', }, }, { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/component_template.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/component_template.ts index 4a7365c729d95..fd4559aec112a 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/component_template.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/component_template.ts @@ -30,13 +30,11 @@ export const createEntityIndexComponentTemplate = ( const name = getComponentTemplateName(id); return esClient.cluster.putComponentTemplate({ name, - body: { - template: { - settings: { - hidden: true, - }, - mappings: indexMappings, + template: { + settings: { + hidden: true, }, + mappings: indexMappings, }, }); }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/ingest_pipeline.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/ingest_pipeline.ts index 1017d04120908..0ceab9db152e1 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/ingest_pipeline.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/entity_store/elasticsearch_assets/ingest_pipeline.ts @@ -138,20 +138,18 @@ export const createPlatformPipeline = async ({ const pipeline = { id: getPlatformPipelineId(description.id), - body: { - _meta: { - managed_by: 'entity_store', - managed: true, - }, - description: `Ingest pipeline for entity definition ${description.id}`, - processors: buildIngestPipeline({ - namespace: options.namespace, - description, - version: description.version, - allEntityFields, - debugMode, - }), + _meta: { + managed_by: 'entity_store', + managed: true, }, + description: `Ingest pipeline for entity definition ${description.id}`, + processors: buildIngestPipeline({ + namespace: options.namespace, + description, + version: description.version, + allEntityFields, + debugMode, + }), }; logger.debug(`Attempting to create pipeline: ${JSON.stringify(pipeline)}`); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.test.ts index 393cfd5c7b498..029179043957d 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.test.ts @@ -181,14 +181,12 @@ const assertIndexTemplate = (namespace: string) => { expect(createOrUpdateIndexTemplate).toHaveBeenCalledWith({ logger, esClient, - template: { + template: expect.objectContaining({ name: `.risk-score.risk-score-${namespace}-index-template`, - body: expect.objectContaining({ - data_stream: { hidden: true }, - index_patterns: [`risk-score.risk-score-${namespace}`], - composed_of: [`.risk-score-mappings-${namespace}`], - }), - }, + data_stream: { hidden: true }, + index_patterns: [`risk-score.risk-score-${namespace}`], + composed_of: [`.risk-score-mappings-${namespace}`], + }), }); }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.ts index 2542e33c92be6..cd965886d5d63 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/risk_score/risk_score_data_client.ts @@ -6,10 +6,10 @@ */ import type { + ClusterPutComponentTemplateRequest, MappingDynamicMapping, Metadata, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { ClusterPutComponentTemplateRequest } from '@elastic/elasticsearch/lib/api/types'; +} from '@elastic/elasticsearch/lib/api/types'; import { createOrUpdateComponentTemplate, createOrUpdateIndexTemplate, @@ -169,23 +169,21 @@ export class RiskScoreDataClient { esClient, template: { name: indexPatterns.template, - body: { - data_stream: { hidden: true }, - index_patterns: [indexPatterns.alias], - composed_of: [nameSpaceAwareMappingsComponentName(namespace)], - template: { - lifecycle: {}, - settings: { - 'index.mapping.total_fields.limit': totalFieldsLimit, - 'index.default_pipeline': getIngestPipelineName(namespace), - }, - mappings: { - dynamic: false, - _meta: indexMetadata, - }, + data_stream: { hidden: true }, + index_patterns: [indexPatterns.alias], + composed_of: [nameSpaceAwareMappingsComponentName(namespace)], + template: { + lifecycle: {}, + settings: { + 'index.mapping.total_fields.limit': totalFieldsLimit, + 'index.default_pipeline': getIngestPipelineName(namespace), + }, + mappings: { + dynamic: false, + _meta: indexMetadata, }, - _meta: indexMetadata, }, + _meta: indexMetadata, }, }); @@ -345,6 +343,7 @@ export class RiskScoreDataClient { const newComponentTemplateName = nameSpaceAwareMappingsComponentName(namespace); await esClient.cluster.putComponentTemplate({ name: newComponentTemplateName, + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 body: oldComponentTemplate.component_template, }); } @@ -356,20 +355,18 @@ export class RiskScoreDataClient { conflicts: 'proceed', ignore_unavailable: true, allow_no_indices: true, - body: { - query: { - bool: { - must_not: { - exists: { - field: 'event.ingested', - }, + query: { + bool: { + must_not: { + exists: { + field: 'event.ingested', }, }, }, - script: { - source: 'ctx._source.event.ingested = ctx._source.@timestamp', - lang: 'painless', - }, + }, + script: { + source: 'ctx._source.event.ingested = ctx._source.@timestamp', + lang: 'painless', }, }, { diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_datastream.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_datastream.ts index ed56a35968bdb..fe426aab29b8e 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_datastream.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_datastream.ts @@ -9,7 +9,7 @@ // The original function created an index, while here we create a datastream. If and when responseOps develops first-party code to work with datastreams (https://github.com/elastic/kibana/issues/140403), this file should be removed. import { get } from 'lodash'; -import type { IndicesSimulateIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { IndicesSimulateIndexTemplateResponse } from '@elastic/elasticsearch/lib/api/types'; import type { Logger, ElasticsearchClient } from '@kbn/core/server'; import { retryTransientEsErrors } from './retry_transient_es_errors'; @@ -50,7 +50,7 @@ const updateTotalFieldLimitSetting = async ({ () => esClient.indices.putSettings({ index, - body: { 'index.mapping.total_fields.limit': totalFieldsLimit }, + settings: { 'index.mapping.total_fields.limit': totalFieldsLimit }, }), { logger } ); @@ -89,6 +89,7 @@ export const updateUnderlyingMapping = async ({ logger, esClient, index }: Updat try { await retryTransientEsErrors( + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 () => esClient.indices.putMapping({ index, body: simulatedMapping }), { logger } ); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_ingest_pipeline.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_ingest_pipeline.ts index 183243e98be95..a062695e9fe29 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_ingest_pipeline.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_ingest_pipeline.ts @@ -20,21 +20,19 @@ export const createEventIngestedFromTimestamp = async ( try { const pipeline = { id: ingestTimestampPipeline, - body: { - _meta: { - managed_by: 'entity_analytics', - managed: true, - }, - description: 'Pipeline for adding timestamp value to event.ingested', - processors: [ - { - set: { - field: 'event.ingested', - value: '{{_ingest.timestamp}}', - }, - }, - ], + _meta: { + managed_by: 'entity_analytics', + managed: true, }, + description: 'Pipeline for adding timestamp value to event.ingested', + processors: [ + { + set: { + field: 'event.ingested', + value: '{{_ingest.timestamp}}', + }, + }, + ], }; await esClient.ingest.putPipeline(pipeline); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_or_update_index.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_or_update_index.ts index a37b43ed5af93..1d8cdbc5cc0ef 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_or_update_index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/entity_analytics/utils/create_or_update_index.ts @@ -40,6 +40,7 @@ export const createOrUpdateIndex = async ({ indices.map(async (index) => { try { await retryTransientEsErrors( + // @ts-expect-error elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 () => esClient.indices.putMapping({ index, body: options.mappings }), { logger } ); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.test.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.test.ts index 296f1384df32d..e6abf87ffc693 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.test.ts @@ -11,7 +11,7 @@ import { getAnomalies } from '.'; const getFiltersFromMock = (mock: jest.Mock) => { const [[searchParams]] = mock.mock.calls; - return searchParams.body.query.bool.filter; + return searchParams.query.bool.filter; }; const getBoolCriteriaFromFilters = (filters: ESFilter[]) => diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.ts index e8eb0f2c19ee6..52b7b4fce683d 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/machine_learning/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { MlAnomalyRecordDoc as Anomaly } from '@kbn/ml-anomaly-utils'; import type { Filter } from '@kbn/es-query'; @@ -37,35 +37,33 @@ export const getAnomalies = async ( export const buildAnomalyQuery = (params: AnomaliesSearchParams): estypes.SearchRequest => { const boolCriteria = buildCriteria(params); return { - body: { - size: params.maxRecords || 100, - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:record', - analyze_wildcard: false, - }, + size: params.maxRecords || 100, + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:record', + analyze_wildcard: false, }, - { term: { is_interim: false } }, - { - bool: { - must: boolCriteria, - }, + }, + { term: { is_interim: false } }, + { + bool: { + must: boolCriteria, }, - ], - must_not: params.exceptionFilter?.query, - }, + }, + ], + must_not: params.exceptionFilter?.query, }, - fields: [ - { - field: '*', - include_unmapped: true, - }, - ], - sort: [{ record_score: { order: 'desc' as const } }], }, + fields: [ + { + field: '*', + include_unmapped: true, + }, + ], + sort: [{ record_score: { order: 'desc' as const } }], }; }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/api/privileges/get_missing_privileges.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/api/privileges/get_missing_privileges.ts index 8d392deadd930..ddd9dff43b1eb 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/api/privileges/get_missing_privileges.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/api/privileges/get_missing_privileges.ts @@ -68,9 +68,7 @@ const readIndexPrivileges = async ( ): Promise => { const response = await esClient.security.hasPrivileges( { - body: { - index: [{ names: [index], privileges: ['read', 'write', 'manage', 'create_index'] }], - }, + index: [{ names: [index], privileges: ['read', 'write', 'manage', 'create_index'] }], }, { meta: true } ); diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/data/sort.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/data/sort.ts index 4ec3e3483813d..4d5ab4d194a77 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/data/sort.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/rules/data/sort.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; export interface RuleMigrationSort { sortField?: string; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/telemetry/helpers.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/telemetry/helpers.ts index 5250b57f9d658..9eb0547535841 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/telemetry/helpers.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/telemetry/helpers.ts @@ -12,7 +12,7 @@ import { merge } from 'lodash'; import { set } from '@kbn/safer-lodash-set'; import type { Logger, LogMeta } from '@kbn/core/server'; import { sha256 } from 'js-sha256'; -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { copyAllowlistedFields, filterList } from './filterlists'; import type { PolicyConfig, PolicyData, SafeEndpointEvent } from '../../../common/endpoint/types'; import type { ITelemetryReceiver } from './receiver'; diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/timeline/routes/notes/get_notes.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/timeline/routes/notes/get_notes.ts index a5110c8dc73b8..8cbaeb5338599 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/timeline/routes/notes/get_notes.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/timeline/routes/notes/get_notes.ts @@ -7,7 +7,7 @@ import type { IKibanaResponse } from '@kbn/core-http-server'; import { transformError } from '@kbn/securitysolution-es-utils'; -import type { SortOrder } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SortOrder } from '@elastic/elasticsearch/lib/api/types'; import { buildRouteValidationWithZod } from '@kbn/zod-helpers'; import type { SavedObjectsFindOptions, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/actions/query.all_actions.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/actions/query.all_actions.dsl.ts index 422d6ebc43792..64dc87ac73c38 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/actions/query.all_actions.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/actions/query.all_actions.dsl.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { ISearchRequestParams } from '@kbn/search-types'; import { OSQUERY_ACTIONS_INDEX } from '@kbn/osquery-plugin/common/constants'; @@ -32,29 +32,27 @@ export const buildResponseActionsQuery = ( allow_no_indices: true, index: [ENDPOINT_ACTIONS_INDEX, OSQUERY_ACTIONS_INDEX], ignore_unavailable: true, - body: { - fields, - _source: false, - query: { - bool: { - minimum_should_match: 2, - should: [ - { term: { type: 'INPUT_ACTION' } }, - { terms: { alert_ids: alertIds } }, - { - terms: { 'data.alert_id': alertIds }, - }, - ] as estypes.QueryDslQueryContainer[], - }, - }, - sort: [ - { - [sort.field]: { - order: sort.order, + fields, + _source: false, + query: { + bool: { + minimum_should_match: 2, + should: [ + { term: { type: 'INPUT_ACTION' } }, + { terms: { alert_ids: alertIds } }, + { + terms: { 'data.alert_id': alertIds }, }, - }, - ], + ] as estypes.QueryDslQueryContainer[], + }, }, + sort: [ + { + [sort.field]: { + order: sort.order, + }, + }, + ], }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/results/query.action_results.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/results/query.action_results.dsl.ts index 3db193815fcff..8eba7503440d2 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/results/query.action_results.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/endpoint/factory/response_actions/results/query.action_results.dsl.ts @@ -17,52 +17,50 @@ export const buildActionResultsQuery = ({ const dslQuery = { allow_no_indices: true, index: [ENDPOINT_ACTION_RESPONSES_INDEX], - body: { - fields, - _source: false, - size: 1, - query: { - term: { action_id: actionId }, - }, + fields, + _source: false, + size: 1, + query: { + term: { action_id: actionId }, + }, + aggs: { aggs: { + global: {}, aggs: { - global: {}, - aggs: { - responses_by_action_id: { - filter: { - bool: { - must: [ - { - match: { - action_id: actionId, - }, + responses_by_action_id: { + filter: { + bool: { + must: [ + { + match: { + action_id: actionId, }, - ], - }, - }, - aggs: { - responses: { - terms: { - script: { - lang: 'painless', - source: - "if (doc.containsKey('error.code') && doc['error.code'].size()==0) { return 'success' } else { return 'error' }", - } as const, }, + ], + }, + }, + aggs: { + responses: { + terms: { + script: { + lang: 'painless', + source: + "if (doc.containsKey('error.code') && doc['error.code'].size()==0) { return 'success' } else { return 'error' }", + } as const, }, }, }, }, }, }, - sort: [ - { - [sort.field]: { - order: sort.order, - }, - }, - ], }, + sort: [ + { + [sort.field]: { + order: sort.order, + }, + }, + ], }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/asset_criticality/query.asset_criticality.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/asset_criticality/query.asset_criticality.dsl.ts index 8b081ecd951d7..10e8d96735572 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/asset_criticality/query.asset_criticality.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/asset_criticality/query.asset_criticality.dsl.ts @@ -38,9 +38,7 @@ export const buildAssetCriticalityQuery = ({ track_total_hits: true, size: querySize, from: cursorStart, - body: { - query: { bool: { filter } }, - }, + query: { bool: { filter } }, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/helpers.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/helpers.ts index 54af298d11a3e..915c51c2523b3 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/helpers.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/helpers.ts @@ -6,7 +6,7 @@ */ import { get, isEmpty } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ENRICHMENT_TYPES, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.test.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.test.ts index 1863503bfcae3..831f921f5182f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.test.ts @@ -12,7 +12,7 @@ describe('buildEventEnrichmentQuery', () => { it('converts each event field/value into a named filter', () => { const options = buildEventEnrichmentRequestOptionsMock(); const query = buildEventEnrichmentQuery(options); - expect(query.body?.query?.bool?.should).toEqual( + expect(query.query?.bool?.should).toEqual( expect.arrayContaining([ { match: { @@ -31,7 +31,7 @@ describe('buildEventEnrichmentQuery', () => { it('filters on indicator events', () => { const options = buildEventEnrichmentRequestOptionsMock(); const query = buildEventEnrichmentQuery(options); - expect(query.body?.query?.bool?.filter).toEqual( + expect(query.query?.bool?.filter).toEqual( expect.arrayContaining([{ term: { 'event.type': 'indicator' } }]) ); }); @@ -39,7 +39,7 @@ describe('buildEventEnrichmentQuery', () => { it('includes the specified timerange', () => { const options = buildEventEnrichmentRequestOptionsMock(); const query = buildEventEnrichmentQuery(options); - expect(query.body?.query?.bool?.filter).toEqual( + expect(query.query?.bool?.filter).toEqual( expect.arrayContaining([ { range: { @@ -57,7 +57,7 @@ describe('buildEventEnrichmentQuery', () => { it('requests all fields', () => { const options = buildEventEnrichmentRequestOptionsMock(); const query = buildEventEnrichmentQuery(options); - expect(query.body?.fields).toEqual([ + expect(query.fields).toEqual([ { field: '*', include_unmapped: true }, { field: '@timestamp', @@ -77,7 +77,7 @@ describe('buildEventEnrichmentQuery', () => { it('excludes _source', () => { const options = buildEventEnrichmentRequestOptionsMock(); const query = buildEventEnrichmentQuery(options); - expect(query.body?._source).toEqual(false); + expect(query._source).toEqual(false); }); it('includes specified filters', () => { @@ -88,6 +88,6 @@ describe('buildEventEnrichmentQuery', () => { const options = buildEventEnrichmentRequestOptionsMock({ filterQuery }); const query = buildEventEnrichmentQuery(options); - expect(query.body?.query?.bool?.filter).toEqual(expect.arrayContaining([filterQuery])); + expect(query.query?.bool?.filter).toEqual(expect.arrayContaining([filterQuery])); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.ts index ec1ca68817f2c..37eb12819ebfc 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/query.ts @@ -33,30 +33,28 @@ export const buildEventEnrichmentQuery = ({ allow_no_indices: true, ignore_unavailable: true, index: defaultIndex, - body: { - _source: false, - fields: [ - { field: '*', include_unmapped: true }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - { - field: 'code_signature.timestamp', - format: 'strict_date_optional_time', - }, - { - field: 'dll.code_signature.timestamp', - format: 'strict_date_optional_time', - }, - ], - stored_fields: ['*'], - query: { - bool: { - should: buildIndicatorShouldClauses(eventFields), - filter, - minimum_should_match: 1, - }, + _source: false, + fields: [ + { field: '*', include_unmapped: true }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + { + field: 'code_signature.timestamp', + format: 'strict_date_optional_time', + }, + { + field: 'dll.code_signature.timestamp', + format: 'strict_date_optional_time', + }, + ], + stored_fields: ['*'], + query: { + bool: { + should: buildIndicatorShouldClauses(eventFields), + filter, + minimum_should_match: 1, }, }, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/response.test.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/response.test.ts index 2591a48f22853..c04c0ba346fdc 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/response.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/event_enrichment/response.test.ts @@ -20,59 +20,57 @@ describe('parseEventEnrichmentResponse', () => { const expectedInspect = { allow_no_indices: true, - body: { - _source: false, - fields: [ - { field: '*', include_unmapped: true }, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - { - field: 'code_signature.timestamp', - format: 'strict_date_optional_time', - }, - { - field: 'dll.code_signature.timestamp', - format: 'strict_date_optional_time', - }, - ], - query: { - bool: { - filter: [ - { bool: { filter: [{ match_all: {} }], must: [], must_not: [], should: [] } }, - { term: { 'event.type': 'indicator' } }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: '2020-09-13T09:00:43.249Z', - lte: '2020-09-14T09:00:43.249Z', - }, + _source: false, + fields: [ + { field: '*', include_unmapped: true }, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + { + field: 'code_signature.timestamp', + format: 'strict_date_optional_time', + }, + { + field: 'dll.code_signature.timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { + bool: { + filter: [ + { bool: { filter: [{ match_all: {} }], must: [], must_not: [], should: [] } }, + { term: { 'event.type': 'indicator' } }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: '2020-09-13T09:00:43.249Z', + lte: '2020-09-14T09:00:43.249Z', }, }, - ], - minimum_should_match: 1, - should: [ - { - match: { - 'threat.indicator.file.hash.md5': { - _name: 'file.hash.md5', - query: '1eee2bf3f56d8abed72da2bc523e7431', - }, + }, + ], + minimum_should_match: 1, + should: [ + { + match: { + 'threat.indicator.file.hash.md5': { + _name: 'file.hash.md5', + query: '1eee2bf3f56d8abed72da2bc523e7431', }, }, - { match: { 'threat.indicator.ip': { _name: 'source.ip', query: '127.0.0.1' } } }, - { - match: { - 'threat.indicator.url.full': { _name: 'url.full', query: 'elastic.co' }, - }, + }, + { match: { 'threat.indicator.ip': { _name: 'source.ip', query: '127.0.0.1' } } }, + { + match: { + 'threat.indicator.url.full': { _name: 'url.full', query: 'elastic.co' }, }, - ], - }, + }, + ], }, - stored_fields: ['*'], }, + stored_fields: ['*'], ignore_unavailable: true, index: ['filebeat-*'], }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.test.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.test.ts index 54663122eea4b..b4cc5a7e12d12 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.test.ts @@ -21,40 +21,38 @@ export const mockOptions: ThreatIntelSourceRequestOptionsInput = { }; export const expectedDsl = { - body: { - aggs: { - dataset: { - terms: { - field: 'event.dataset', - }, - aggs: { - name: { - terms: { - field: 'threat.feed.name', - }, + aggs: { + dataset: { + terms: { + field: 'event.dataset', + }, + aggs: { + name: { + terms: { + field: 'threat.feed.name', }, - dashboard: { - terms: { - field: 'threat.feed.dashboard_id', - }, + }, + dashboard: { + terms: { + field: 'threat.feed.dashboard_id', }, }, }, }, - query: { - bool: { - filter: [ - { - range: { - '@timestamp': { - gte: '2020-09-06T15:23:52.757Z', - lte: '2020-09-07T15:23:52.757Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { + range: { + '@timestamp': { + gte: '2020-09-06T15:23:52.757Z', + lte: '2020-09-07T15:23:52.757Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, }, ignore_unavailable: true, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.ts index 0ea0ddbb3a5a9..08c1bbc6ecc40 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/cti/threat_intel_source/query.threat_intel_source.dsl.ts @@ -31,26 +31,24 @@ export const buildTiDataSourceQuery = ({ allow_no_indices: true, ignore_unavailable: true, track_total_hits: true, - body: { - aggs: { - dataset: { - terms: { field: 'event.dataset' }, - aggs: { - name: { - terms: { field: 'threat.feed.name' }, - }, - dashboard: { - terms: { - field: 'threat.feed.dashboard_id', - }, + aggs: { + dataset: { + terms: { field: 'event.dataset' }, + aggs: { + name: { + terms: { field: 'threat.feed.name' }, + }, + dashboard: { + terms: { + field: 'threat.feed.dashboard_id', }, }, }, }, - query: { - bool: { - filter, - }, + }, + query: { + bool: { + filter, }, }, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/__mocks__/index.ts index 9c5cbdf35b89e..12b2f939b4ed9 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/__mocks__/index.ts @@ -482,52 +482,50 @@ export const formattedSearchStrategyResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - host_count: { cardinality: { field: 'host.name' } }, - host_data: { - terms: { size: 10, field: 'host.name', order: { lastSeen: 'desc' } }, - aggs: { - lastSeen: { max: { field: '@timestamp' } }, - os: { - top_hits: { - size: 1, - sort: [{ '@timestamp': { order: 'desc' } }], - _source: false, - }, + aggregations: { + host_count: { cardinality: { field: 'host.name' } }, + host_data: { + terms: { size: 10, field: 'host.name', order: { lastSeen: 'desc' } }, + aggs: { + lastSeen: { max: { field: '@timestamp' } }, + os: { + top_hits: { + size: 1, + sort: [{ '@timestamp': { order: 'desc' } }], + _source: false, }, }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-03T09:15:21.415Z', - lte: '2020-09-04T09:15:21.415Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-03T09:15:21.415Z', + lte: '2020-09-04T09:15:21.415Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, - fields: [ - 'host.id', - 'host.name', - 'host.os.name', - 'host.os.version', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'host.id', + 'host.name', + 'host.os.name', + 'host.os.version', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, }, null, 2 @@ -648,52 +646,50 @@ export const mockBuckets: HostAggEsItem = { export const expectedDsl = { allow_no_indices: true, track_total_hits: false, - body: { - aggregations: { - host_count: { cardinality: { field: 'host.name' } }, - host_data: { - aggs: { - lastSeen: { max: { field: '@timestamp' } }, - os: { - top_hits: { - _source: false, - size: 1, - sort: [{ '@timestamp': { order: 'desc' } }], - }, + aggregations: { + host_count: { cardinality: { field: 'host.name' } }, + host_data: { + aggs: { + lastSeen: { max: { field: '@timestamp' } }, + os: { + top_hits: { + _source: false, + size: 1, + sort: [{ '@timestamp': { order: 'desc' } }], }, }, - terms: { field: 'host.name', order: { lastSeen: 'desc' }, size: 10 }, }, + terms: { field: 'host.name', order: { lastSeen: 'desc' }, size: 10 }, }, - query: { - bool: { - filter: [ - { bool: { filter: [{ match_all: {} }], must: [], must_not: [], should: [] } }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: '2020-09-03T09:15:21.415Z', - lte: '2020-09-04T09:15:21.415Z', - }, + }, + query: { + bool: { + filter: [ + { bool: { filter: [{ match_all: {} }], must: [], must_not: [], should: [] } }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: '2020-09-03T09:15:21.415Z', + lte: '2020-09-04T09:15:21.415Z', }, }, - ], - }, + }, + ], }, - _source: false, - fields: [ - 'host.id', - 'host.name', - 'host.os.name', - 'host.os.version', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'host.id', + 'host.name', + 'host.os.name', + 'host.os.version', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, ignore_unavailable: true, index: [ 'apm-*-transaction*', diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/query.all_hosts.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/query.all_hosts.dsl.ts index 79c055584b5fa..00419f15bbe1c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/query.all_hosts.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/all/query.all_hosts.dsl.ts @@ -44,40 +44,38 @@ export const buildHostsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - ...agg, - host_data: { - terms: { size: querySize, field: 'host.name', order: getQueryOrder(sort) }, - aggs: { - lastSeen: { max: { field: '@timestamp' } }, - os: { - top_hits: { - size: 1, - sort: [ - { - '@timestamp': { - order: 'desc' as const, - }, + aggregations: { + ...agg, + host_data: { + terms: { size: querySize, field: 'host.name', order: getQueryOrder(sort) }, + aggs: { + lastSeen: { max: { field: '@timestamp' } }, + os: { + top_hits: { + size: 1, + sort: [ + { + '@timestamp': { + order: 'desc' as const, }, - ], - _source: false, - }, + }, + ], + _source: false, }, }, }, }, - query: { bool: { filter } }, - _source: false, - fields: [ - ...esFields, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + query: { bool: { filter } }, + _source: false, + fields: [ + ...esFields, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/__mocks__/index.ts index 257708e66925c..24550f2694f5b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/__mocks__/index.ts @@ -440,119 +440,117 @@ export const formattedSearchStrategyResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - host_architecture: { - terms: { field: 'host.architecture', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, + aggregations: { + host_architecture: { + terms: { field: 'host.architecture', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_id: { + terms: { field: 'host.id', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_ip: { + terms: { + script: { source: "doc['host.ip']", lang: 'painless' }, + size: 10, + order: { timestamp: 'desc' }, }, - host_id: { - terms: { field: 'host.id', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - host_ip: { - terms: { - script: { source: "doc['host.ip']", lang: 'painless' }, - size: 10, - order: { timestamp: 'desc' }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_mac: { + terms: { field: 'host.mac', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_name: { + terms: { field: 'host.name', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_os_family: { + terms: { field: 'host.os.family', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_os_name: { + terms: { field: 'host.os.name', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_os_platform: { + terms: { field: 'host.os.platform', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + host_os_version: { + terms: { field: 'host.os.version', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + cloud_instance_id: { + terms: { field: 'cloud.instance.id', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + cloud_machine_type: { + terms: { field: 'cloud.machine.type', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + cloud_provider: { + terms: { field: 'cloud.provider', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + cloud_region: { + terms: { field: 'cloud.region', size: 10, order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + endpoint_id: { + filter: { + term: { + 'agent.type': 'endpoint', }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - host_mac: { - terms: { field: 'host.mac', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - host_name: { - terms: { field: 'host.name', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - host_os_family: { - terms: { field: 'host.os.family', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - host_os_name: { - terms: { field: 'host.os.name', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, }, - host_os_platform: { - terms: { field: 'host.os.platform', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - host_os_version: { - terms: { field: 'host.os.version', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - cloud_instance_id: { - terms: { field: 'cloud.instance.id', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - cloud_machine_type: { - terms: { field: 'cloud.machine.type', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - cloud_provider: { - terms: { field: 'cloud.provider', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - cloud_region: { - terms: { field: 'cloud.region', size: 10, order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - endpoint_id: { - filter: { - term: { - 'agent.type': 'endpoint', - }, - }, - aggs: { - value: { - terms: { - field: 'agent.id', - }, + aggs: { + value: { + terms: { + field: 'agent.id', }, }, }, }, - query: { - bool: { - filter: [ - { term: { 'host.name': 'bastion00.siem.estc.dev' } }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: '2020-09-02T15:17:13.678Z', - lte: '2020-09-03T15:17:13.678Z', - }, + }, + query: { + bool: { + filter: [ + { term: { 'host.name': 'bastion00.siem.estc.dev' } }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: '2020-09-02T15:17:13.678Z', + lte: '2020-09-03T15:17:13.678Z', }, }, - ], - }, + }, + ], + }, + }, + _source: false, + fields: [ + 'host.architecture', + 'host.id', + 'host.ip', + 'host.mac', + 'host.name', + 'host.os.family', + 'host.os.name', + 'host.os.platform', + 'host.os.version', + 'cloud.instance.id', + 'cloud.machine.type', + 'cloud.provider', + 'cloud.region', + 'agent.type', + 'agent.id', + { + field: '@timestamp', + format: 'strict_date_optional_time', }, - _source: false, - fields: [ - 'host.architecture', - 'host.id', - 'host.ip', - 'host.mac', - 'host.name', - 'host.os.family', - 'host.os.name', - 'host.os.platform', - 'host.os.version', - 'cloud.instance.id', - 'cloud.machine.type', - 'cloud.provider', - 'cloud.region', - 'agent.type', - 'agent.id', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, - }, + ], + size: 0, }, null, 2 @@ -576,276 +574,274 @@ export const expectedDsl = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - endpoint_id: { - filter: { - term: { - 'agent.type': 'endpoint', - }, + aggregations: { + endpoint_id: { + filter: { + term: { + 'agent.type': 'endpoint', }, - aggs: { - value: { - terms: { - field: 'agent.id', - }, + }, + aggs: { + value: { + terms: { + field: 'agent.id', }, }, }, - host_architecture: { - terms: { - field: 'host.architecture', - size: 10, - order: { - timestamp: 'desc', - }, + }, + host_architecture: { + terms: { + field: 'host.architecture', + size: 10, + order: { + timestamp: 'desc', }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, + }, + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, }, - host_id: { - terms: { - field: 'host.id', - size: 10, - order: { - timestamp: 'desc', - }, + }, + host_id: { + terms: { + field: 'host.id', + size: 10, + order: { + timestamp: 'desc', }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, + }, + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, }, - host_ip: { - terms: { - script: { - source: "doc['host.ip']", - lang: 'painless', - }, - size: 10, - order: { - timestamp: 'desc', - }, + }, + host_ip: { + terms: { + script: { + source: "doc['host.ip']", + lang: 'painless', }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + size: 10, + order: { + timestamp: 'desc', }, }, - host_mac: { - terms: { - field: 'host.mac', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + host_mac: { + terms: { + field: 'host.mac', + size: 10, + order: { + timestamp: 'desc', }, }, - host_name: { - terms: { - field: 'host.name', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + host_name: { + terms: { + field: 'host.name', + size: 10, + order: { + timestamp: 'desc', }, }, - host_os_family: { - terms: { - field: 'host.os.family', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + host_os_family: { + terms: { + field: 'host.os.family', + size: 10, + order: { + timestamp: 'desc', }, }, - host_os_name: { - terms: { - field: 'host.os.name', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + host_os_name: { + terms: { + field: 'host.os.name', + size: 10, + order: { + timestamp: 'desc', }, }, - host_os_platform: { - terms: { - field: 'host.os.platform', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + host_os_platform: { + terms: { + field: 'host.os.platform', + size: 10, + order: { + timestamp: 'desc', }, }, - host_os_version: { - terms: { - field: 'host.os.version', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + host_os_version: { + terms: { + field: 'host.os.version', + size: 10, + order: { + timestamp: 'desc', }, }, - cloud_instance_id: { - terms: { - field: 'cloud.instance.id', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + cloud_instance_id: { + terms: { + field: 'cloud.instance.id', + size: 10, + order: { + timestamp: 'desc', }, }, - cloud_machine_type: { - terms: { - field: 'cloud.machine.type', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + cloud_machine_type: { + terms: { + field: 'cloud.machine.type', + size: 10, + order: { + timestamp: 'desc', }, }, - cloud_provider: { - terms: { - field: 'cloud.provider', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, - }, + }, + }, + cloud_provider: { + terms: { + field: 'cloud.provider', + size: 10, + order: { + timestamp: 'desc', }, }, - cloud_region: { - terms: { - field: 'cloud.region', - size: 10, - order: { - timestamp: 'desc', + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, - aggs: { - timestamp: { - max: { - field: '@timestamp', - }, + }, + }, + cloud_region: { + terms: { + field: 'cloud.region', + size: 10, + order: { + timestamp: 'desc', + }, + }, + aggs: { + timestamp: { + max: { + field: '@timestamp', }, }, }, }, - query: { - bool: { - filter: [ - { - term: { - 'host.name': 'bastion00.siem.estc.dev', - }, + }, + query: { + bool: { + filter: [ + { + term: { + 'host.name': 'bastion00.siem.estc.dev', }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: '2020-09-02T15:17:13.678Z', - lte: '2020-09-03T15:17:13.678Z', - }, + }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: '2020-09-02T15:17:13.678Z', + lte: '2020-09-03T15:17:13.678Z', }, }, - ], - }, + }, + ], }, - _source: false, - fields: [ - 'host.architecture', - 'host.id', - 'host.ip', - 'host.mac', - 'host.name', - 'host.os.family', - 'host.os.name', - 'host.os.platform', - 'host.os.version', - 'cloud.instance.id', - 'cloud.machine.type', - 'cloud.provider', - 'cloud.region', - 'agent.type', - 'agent.id', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'host.architecture', + 'host.id', + 'host.ip', + 'host.mac', + 'host.name', + 'host.os.family', + 'host.os.name', + 'host.os.platform', + 'host.os.version', + 'cloud.instance.id', + 'cloud.machine.type', + 'cloud.provider', + 'cloud.region', + 'agent.type', + 'agent.id', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/query.host_details.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/query.host_details.dsl.ts index 2c68a3b6217bc..c318e85b8d903 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/query.host_details.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/details/query.host_details.dsl.ts @@ -39,37 +39,35 @@ export const buildHostDetailsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - ...buildFieldsTermAggregation(esFields.filter((field) => !['@timestamp'].includes(field))), - endpoint_id: { - filter: { - term: { - 'agent.type': 'endpoint', - }, + aggregations: { + ...buildFieldsTermAggregation(esFields.filter((field) => !['@timestamp'].includes(field))), + endpoint_id: { + filter: { + term: { + 'agent.type': 'endpoint', }, - aggs: { - value: { - terms: { - field: 'agent.id', - }, + }, + aggs: { + value: { + terms: { + field: 'agent.id', }, }, }, }, - query: { bool: { filter } }, - _source: false, - fields: [ - ...esFields, - 'agent.type', - 'agent.id', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + query: { bool: { filter } }, + _source: false, + fields: [ + ...esFields, + 'agent.type', + 'agent.id', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/__mocks__/index.ts index b5fc2ea7dbf73..201e69ccdcc1d 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/__mocks__/index.ts @@ -1560,137 +1560,135 @@ export const formattedSearchStrategyResponse = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - process_count: { cardinality: { field: 'process.name' } }, - group_by_process: { - terms: { - size: 10, - field: 'process.name', - order: [{ host_count: 'asc' }, { _count: 'asc' }, { _key: 'asc' }], - }, - aggregations: { - process: { - top_hits: { - size: 1, - sort: [{ '@timestamp': { order: 'desc' } }], - _source: false, - fields: [ - 'process.args', - 'process.name', - 'user.id', - 'user.name', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - }, + aggregations: { + process_count: { cardinality: { field: 'process.name' } }, + group_by_process: { + terms: { + size: 10, + field: 'process.name', + order: [{ host_count: 'asc' }, { _count: 'asc' }, { _key: 'asc' }], + }, + aggregations: { + process: { + top_hits: { + size: 1, + sort: [{ '@timestamp': { order: 'desc' } }], + _source: false, + fields: [ + 'process.args', + 'process.name', + 'user.id', + 'user.name', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }, - host_count: { cardinality: { field: 'host.name' } }, - hosts: { - terms: { field: 'host.name' }, - aggregations: { - host: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'host.name', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - }, + }, + host_count: { cardinality: { field: 'host.name' } }, + hosts: { + terms: { field: 'host.name' }, + aggregations: { + host: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'host.name', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }, }, }, }, }, }, - query: { - bool: { - should: [ - { - bool: { - filter: [ - { term: { 'agent.type': 'auditbeat' } }, - { term: { 'event.module': 'auditd' } }, - { term: { 'event.action': 'executed' } }, - ], - }, + }, + query: { + bool: { + should: [ + { + bool: { + filter: [ + { term: { 'agent.type': 'auditbeat' } }, + { term: { 'event.module': 'auditd' } }, + { term: { 'event.action': 'executed' } }, + ], }, - { - bool: { - filter: [ - { term: { 'agent.type': 'auditbeat' } }, - { term: { 'event.module': 'system' } }, - { term: { 'event.dataset': 'process' } }, - { term: { 'event.action': 'process_started' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'agent.type': 'auditbeat' } }, + { term: { 'event.module': 'system' } }, + { term: { 'event.dataset': 'process' } }, + { term: { 'event.action': 'process_started' } }, + ], }, - { - bool: { - filter: [ - { term: { 'agent.type': 'winlogbeat' } }, - { term: { 'event.code': '4688' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'agent.type': 'winlogbeat' } }, + { term: { 'event.code': '4688' } }, + ], }, - { - bool: { - filter: [ - { term: { 'winlog.event_id': 1 } }, - { term: { 'winlog.channel': 'Microsoft-Windows-Sysmon/Operational' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'winlog.event_id': 1 } }, + { term: { 'winlog.channel': 'Microsoft-Windows-Sysmon/Operational' } }, + ], }, - { - bool: { - filter: [ - { term: { 'event.type': 'process_start' } }, - { term: { 'event.category': 'process' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'event.type': 'process_start' } }, + { term: { 'event.category': 'process' } }, + ], }, - { - bool: { - filter: [ - { term: { 'event.category': 'process' } }, - { term: { 'event.type': 'start' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'event.category': 'process' } }, + { term: { 'event.type': 'start' } }, + ], }, - ], - minimum_should_match: 1, - filter: [ - { - bool: { - must: [], - filter: [ - { match_all: {} }, - { match_phrase: { 'host.name': { query: 'siem-kibana' } } }, - ], - should: [], - must_not: [], - }, + }, + ], + minimum_should_match: 1, + filter: [ + { + bool: { + must: [], + filter: [ + { match_all: {} }, + { match_phrase: { 'host.name': { query: 'siem-kibana' } } }, + ], + should: [], + must_not: [], }, - { - range: { - '@timestamp': { - gte: '2020-09-06T15:23:52.757Z', - lte: '2020-09-07T15:23:52.757Z', - format: 'strict_date_optional_time', - }, + }, + { + range: { + '@timestamp': { + gte: '2020-09-06T15:23:52.757Z', + lte: '2020-09-07T15:23:52.757Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, }, + _source: false, size: 0, track_total_hits: false, }, @@ -1720,137 +1718,132 @@ export const expectedDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - process_count: { cardinality: { field: 'process.name' } }, - group_by_process: { - terms: { - size: 10, - field: 'process.name', - order: [{ host_count: 'asc' }, { _count: 'asc' }, { _key: 'asc' }], - }, - aggregations: { - process: { - top_hits: { - size: 1, - sort: [{ '@timestamp': { order: 'desc' } }], - _source: false, - fields: [ - 'process.args', - 'process.name', - 'user.id', - 'user.name', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - }, + aggregations: { + process_count: { cardinality: { field: 'process.name' } }, + group_by_process: { + terms: { + size: 10, + field: 'process.name', + order: [{ host_count: 'asc' }, { _count: 'asc' }, { _key: 'asc' }], + }, + aggregations: { + process: { + top_hits: { + size: 1, + sort: [{ '@timestamp': { order: 'desc' } }], + _source: false, + fields: [ + 'process.args', + 'process.name', + 'user.id', + 'user.name', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }, - host_count: { cardinality: { field: 'host.name' } }, - hosts: { - terms: { field: 'host.name' }, - aggregations: { - host: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'host.name', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - }, + }, + host_count: { cardinality: { field: 'host.name' } }, + hosts: { + terms: { field: 'host.name' }, + aggregations: { + host: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'host.name', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }, }, }, }, }, }, - query: { - bool: { - should: [ - { - bool: { - filter: [ - { term: { 'agent.type': 'auditbeat' } }, - { term: { 'event.module': 'auditd' } }, - { term: { 'event.action': 'executed' } }, - ], - }, + }, + query: { + bool: { + should: [ + { + bool: { + filter: [ + { term: { 'agent.type': 'auditbeat' } }, + { term: { 'event.module': 'auditd' } }, + { term: { 'event.action': 'executed' } }, + ], }, - { - bool: { - filter: [ - { term: { 'agent.type': 'auditbeat' } }, - { term: { 'event.module': 'system' } }, - { term: { 'event.dataset': 'process' } }, - { term: { 'event.action': 'process_started' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'agent.type': 'auditbeat' } }, + { term: { 'event.module': 'system' } }, + { term: { 'event.dataset': 'process' } }, + { term: { 'event.action': 'process_started' } }, + ], }, - { - bool: { - filter: [ - { term: { 'agent.type': 'winlogbeat' } }, - { term: { 'event.code': '4688' } }, - ], - }, + }, + { + bool: { + filter: [{ term: { 'agent.type': 'winlogbeat' } }, { term: { 'event.code': '4688' } }], }, - { - bool: { - filter: [ - { term: { 'winlog.event_id': 1 } }, - { term: { 'winlog.channel': 'Microsoft-Windows-Sysmon/Operational' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'winlog.event_id': 1 } }, + { term: { 'winlog.channel': 'Microsoft-Windows-Sysmon/Operational' } }, + ], }, - { - bool: { - filter: [ - { term: { 'event.type': 'process_start' } }, - { term: { 'event.category': 'process' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'event.type': 'process_start' } }, + { term: { 'event.category': 'process' } }, + ], }, - { - bool: { - filter: [ - { term: { 'event.category': 'process' } }, - { term: { 'event.type': 'start' } }, - ], - }, + }, + { + bool: { + filter: [ + { term: { 'event.category': 'process' } }, + { term: { 'event.type': 'start' } }, + ], }, - ], - minimum_should_match: 1, - filter: [ - { - bool: { - must: [], - filter: [ - { match_all: {} }, - { match_phrase: { 'host.name': { query: 'siem-kibana' } } }, - ], - should: [], - must_not: [], - }, + }, + ], + minimum_should_match: 1, + filter: [ + { + bool: { + must: [], + filter: [ + { match_all: {} }, + { match_phrase: { 'host.name': { query: 'siem-kibana' } } }, + ], + should: [], + must_not: [], }, - { - range: { - '@timestamp': { - gte: '2020-09-06T15:23:52.757Z', - lte: '2020-09-07T15:23:52.757Z', - format: 'strict_date_optional_time', - }, + }, + { + range: { + '@timestamp': { + gte: '2020-09-06T15:23:52.757Z', + lte: '2020-09-07T15:23:52.757Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, }, + _source: false, size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts index c7364dd8b375d..70b026b8a1965 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { hostFieldsMap, processFieldsMap, userFieldsMap } from '@kbn/securitysolution-ecs'; import type { HostUncommonProcessesRequestOptions } from '../../../../../../../common/api/search_strategy'; import { createQueryFilterClauses } from '../../../../../../utils/build_query'; @@ -49,189 +49,187 @@ export const buildQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: { - ...agg, - group_by_process: { - terms: { - size: querySize, - field: 'process.name', - order: [ - { - host_count: 'asc' as const, - }, - { - _count: 'asc' as const, - }, - { - _key: 'asc' as const, - }, - ] as estypes.AggregationsAggregateOrder, + aggregations: { + ...agg, + group_by_process: { + terms: { + size: querySize, + field: 'process.name', + order: [ + { + host_count: 'asc' as const, + }, + { + _count: 'asc' as const, + }, + { + _key: 'asc' as const, + }, + ] as estypes.AggregationsAggregateOrder, + }, + aggregations: { + process: { + top_hits: { + size: 1, + sort: [{ '@timestamp': { order: 'desc' as const } }], + _source: false, + fields: [ + ...processUserFields, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + }, }, - aggregations: { - process: { - top_hits: { - size: 1, - sort: [{ '@timestamp': { order: 'desc' as const } }], - _source: false, - fields: [ - ...processUserFields, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - }, + host_count: { + cardinality: { + field: 'host.name', }, - host_count: { - cardinality: { - field: 'host.name', - }, + }, + hosts: { + terms: { + field: 'host.name', }, - hosts: { - terms: { - field: 'host.name', - }, - aggregations: { - host: { - top_hits: { - size: 1, - _source: false, - fields: [ - ...hostFields, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - }, + aggregations: { + host: { + top_hits: { + size: 1, + _source: false, + fields: [ + ...hostFields, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], }, }, }, }, }, }, - query: { - bool: { - should: [ - { - bool: { - filter: [ - { - term: { - 'agent.type': 'auditbeat', - }, + }, + query: { + bool: { + should: [ + { + bool: { + filter: [ + { + term: { + 'agent.type': 'auditbeat', }, - { - term: { - 'event.module': 'auditd', - }, + }, + { + term: { + 'event.module': 'auditd', }, - { - term: { - 'event.action': 'executed', - }, + }, + { + term: { + 'event.action': 'executed', }, - ] as estypes.QueryDslQueryContainer[], - }, + }, + ] as estypes.QueryDslQueryContainer[], }, - { - bool: { - filter: [ - { - term: { - 'agent.type': 'auditbeat', - }, + }, + { + bool: { + filter: [ + { + term: { + 'agent.type': 'auditbeat', }, - { - term: { - 'event.module': 'system', - }, + }, + { + term: { + 'event.module': 'system', }, - { - term: { - 'event.dataset': 'process', - }, + }, + { + term: { + 'event.dataset': 'process', }, - { - term: { - 'event.action': 'process_started', - }, + }, + { + term: { + 'event.action': 'process_started', }, - ] as estypes.QueryDslQueryContainer[], - }, + }, + ] as estypes.QueryDslQueryContainer[], }, - { - bool: { - filter: [ - { - term: { - 'agent.type': 'winlogbeat', - }, + }, + { + bool: { + filter: [ + { + term: { + 'agent.type': 'winlogbeat', }, - { - term: { - 'event.code': '4688', - }, + }, + { + term: { + 'event.code': '4688', }, - ], - }, + }, + ], }, - { - bool: { - filter: [ - { - term: { - 'winlog.event_id': 1, - }, + }, + { + bool: { + filter: [ + { + term: { + 'winlog.event_id': 1, }, - { - term: { - 'winlog.channel': 'Microsoft-Windows-Sysmon/Operational', - }, + }, + { + term: { + 'winlog.channel': 'Microsoft-Windows-Sysmon/Operational', }, - ], - }, + }, + ], }, - { - bool: { - filter: [ - { - term: { - 'event.type': 'process_start', - }, + }, + { + bool: { + filter: [ + { + term: { + 'event.type': 'process_start', }, - { - term: { - 'event.category': 'process', - }, + }, + { + term: { + 'event.category': 'process', }, - ], - }, + }, + ], }, - { - bool: { - filter: [ - { - term: { - 'event.category': 'process', - }, + }, + { + bool: { + filter: [ + { + term: { + 'event.category': 'process', }, - { - term: { - 'event.type': 'start', - }, + }, + { + term: { + 'event.type': 'start', }, - ], - }, + }, + ], }, - ], - minimum_should_match: 1, - filter, - }, + }, + ], + minimum_should_match: 1, + filter, }, - _source: false, }, + _source: false, size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/__mocks__/index.ts index 86cbb97ed68b9..e8a5e07ee9c48 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/__mocks__/index.ts @@ -125,24 +125,22 @@ export const formattedSearchStrategyFirstResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter: [{ term: { 'host.name': 'siem-kibana' } }] } }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - sort: [ - { - '@timestamp': { - order: Direction.asc, - }, + query: { bool: { filter: [{ term: { 'host.name': 'siem-kibana' } }] } }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, + sort: [ + { + '@timestamp': { + order: Direction.asc, }, - ], - }, + }, + ], }, null, 2 @@ -194,24 +192,22 @@ export const formattedSearchStrategyLastResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter: [{ term: { 'host.name': 'siem-kibana' } }] } }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - sort: [ - { - '@timestamp': { - order: Direction.desc, - }, + query: { bool: { filter: [{ term: { 'host.name': 'siem-kibana' } }] } }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, + sort: [ + { + '@timestamp': { + order: Direction.desc, }, - ], - }, + }, + ], }, null, 2 @@ -235,16 +231,14 @@ export const expectedDsl = { ], ignore_unavailable: true, track_total_hits: false, - body: { - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - query: { bool: { filter: [{ term: { 'host.name': 'siem-kibana' } }] } }, - size: 1, - sort: [{ '@timestamp': { order: Direction.asc } }], - }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + query: { bool: { filter: [{ term: { 'host.name': 'siem-kibana' } }] } }, + size: 1, + sort: [{ '@timestamp': { order: Direction.asc } }], }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/query.first_or_last_seen.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/query.first_or_last_seen.dsl.ts index 8ea331207d302..738eb6133fcfd 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/query.first_or_last_seen.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/last_first_seen/query.first_or_last_seen.dsl.ts @@ -19,24 +19,22 @@ export const buildFirstOrLastSeenQuery = (options: FirstLastSeenRequestOptions) index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter } }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', + query: { bool: { filter } }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, + sort: [ + { + '@timestamp': { + order, }, - ], - size: 1, - sort: [ - { - '@timestamp': { - order, - }, - }, - ], - }, + }, + ], }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/__mocks__/index.ts index 919437b3723c6..f57b504d85f39 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/__mocks__/index.ts @@ -211,118 +211,116 @@ export const formattedSearchStrategyResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - source: { - filter: { term: { 'source.ip': '35.196.65.164' } }, - aggs: { - as: { - filter: { exists: { field: 'source.as' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'source.as*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + aggs: { + source: { + filter: { term: { 'source.ip': '35.196.65.164' } }, + aggs: { + as: { + filter: { exists: { field: 'source.as' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'source.as*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, - geo: { - filter: { exists: { field: 'source.geo' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'source.geo*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + geo: { + filter: { exists: { field: 'source.geo' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'source.geo*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, }, }, - destination: { - filter: { term: { 'destination.ip': '35.196.65.164' } }, - aggs: { - as: { - filter: { exists: { field: 'destination.as' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'destination.as*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + destination: { + filter: { term: { 'destination.ip': '35.196.65.164' } }, + aggs: { + as: { + filter: { exists: { field: 'destination.as' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'destination.as*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, - geo: { - filter: { exists: { field: 'destination.geo' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'destination.geo*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + geo: { + filter: { exists: { field: 'destination.geo' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'destination.geo*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, }, }, - host: { - filter: { term: { 'host.ip': '35.196.65.164' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'host*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + host: { + filter: { term: { 'host.ip': '35.196.65.164' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'host*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, }, - query: { bool: { should: [] } }, - size: 0, - _source: false, }, + query: { bool: { should: [] } }, + size: 0, + _source: false, }, null, 2 @@ -384,116 +382,114 @@ export const expectedDsl = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - source: { - filter: { term: { 'source.ip': '35.196.65.164' } }, - aggs: { - as: { - filter: { exists: { field: 'source.as' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'source.as*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + aggs: { + source: { + filter: { term: { 'source.ip': '35.196.65.164' } }, + aggs: { + as: { + filter: { exists: { field: 'source.as' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'source.as*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, - geo: { - filter: { exists: { field: 'source.geo' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'source.geo*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + geo: { + filter: { exists: { field: 'source.geo' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'source.geo*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, }, }, - destination: { - filter: { term: { 'destination.ip': '35.196.65.164' } }, - aggs: { - as: { - filter: { exists: { field: 'destination.as' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'destination.as*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + destination: { + filter: { term: { 'destination.ip': '35.196.65.164' } }, + aggs: { + as: { + filter: { exists: { field: 'destination.as' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'destination.as*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, - geo: { - filter: { exists: { field: 'destination.geo' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'destination.geo*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + geo: { + filter: { exists: { field: 'destination.geo' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'destination.geo*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, }, }, - host: { - filter: { term: { 'host.ip': '35.196.65.164' } }, - aggs: { - results: { - top_hits: { - size: 1, - _source: false, - fields: [ - 'host*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - sort: [{ '@timestamp': 'desc' }], - }, + }, + host: { + filter: { term: { 'host.ip': '35.196.65.164' } }, + aggs: { + results: { + top_hits: { + size: 1, + _source: false, + fields: [ + 'host*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + sort: [{ '@timestamp': 'desc' }], }, }, }, }, - query: { bool: { should: [] } }, - size: 0, - _source: false, }, + query: { bool: { should: [] } }, + size: 0, + _source: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/query.details_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/query.details_network.dsl.ts index 3d964fd81e583..6513ebc15af0c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/query.details_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/details/query.details_network.dsl.ts @@ -113,20 +113,18 @@ export const buildNetworkDetailsQuery = ({ defaultIndex, ip }: NetworkDetailsReq index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - ...getAggs('source', ip), - ...getAggs('destination', ip), - ...getHostAggs(ip), - }, - query: { - bool: { - should: [], - }, + aggs: { + ...getAggs('source', ip), + ...getAggs('destination', ip), + ...getHostAggs(ip), + }, + query: { + bool: { + should: [], }, - size: 0, - _source: false, }, + size: 0, + _source: false, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/__mocks__/index.ts index 2b13c84ab869b..a813b16a7b315 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/__mocks__/index.ts @@ -143,62 +143,60 @@ export const formattedSearchStrategyResponse = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - dns_count: { cardinality: { field: 'dns.question.registered_domain' } }, - dns_name_query_count: { - terms: { - field: 'dns.question.registered_domain', - size: 1000000, - }, - aggs: { + aggregations: { + dns_count: { cardinality: { field: 'dns.question.registered_domain' } }, + dns_name_query_count: { + terms: { + field: 'dns.question.registered_domain', + size: 1000000, + }, + aggs: { + bucket_sort: { bucket_sort: { - bucket_sort: { - sort: [ - { - unique_domains: { - order: 'desc', - }, + sort: [ + { + unique_domains: { + order: 'desc', }, - { _key: { order: 'asc' } }, - ], - from: 0, - size: 10, - }, + }, + { _key: { order: 'asc' } }, + ], + from: 0, + size: 10, }, - unique_domains: { cardinality: { field: 'dns.question.name' } }, - dns_bytes_in: { sum: { field: 'source.bytes' } }, - dns_bytes_out: { sum: { field: 'destination.bytes' } }, }, + unique_domains: { cardinality: { field: 'dns.question.name' } }, + dns_bytes_in: { sum: { field: 'source.bytes' } }, + dns_bytes_out: { sum: { field: 'destination.bytes' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:00:43.249Z', - lte: '2020-09-14T09:00:43.249Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:00:43.249Z', + lte: '2020-09-14T09:00:43.249Z', + format: 'strict_date_optional_time', }, }, - ], - must_not: [{ term: { 'dns.question.type': { value: 'PTR' } } }], - }, + }, + ], + must_not: [{ term: { 'dns.question.type': { value: 'PTR' } } }], }, - _source: false, - fields: [ - 'dns.question.registered_domain', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'dns.question.registered_domain', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }, null, @@ -223,61 +221,59 @@ export const expectedDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - dns_count: { cardinality: { field: 'dns.question.registered_domain' } }, - dns_name_query_count: { - terms: { - field: 'dns.question.registered_domain', - size: 1000000, - }, - aggs: { + aggregations: { + dns_count: { cardinality: { field: 'dns.question.registered_domain' } }, + dns_name_query_count: { + terms: { + field: 'dns.question.registered_domain', + size: 1000000, + }, + aggs: { + bucket_sort: { bucket_sort: { - bucket_sort: { - sort: [ - { - unique_domains: { - order: 'desc', - }, + sort: [ + { + unique_domains: { + order: 'desc', }, - { _key: { order: 'asc' } }, - ], - from: 0, - size: 10, - }, + }, + { _key: { order: 'asc' } }, + ], + from: 0, + size: 10, }, - unique_domains: { cardinality: { field: 'dns.question.name' } }, - dns_bytes_in: { sum: { field: 'source.bytes' } }, - dns_bytes_out: { sum: { field: 'destination.bytes' } }, }, + unique_domains: { cardinality: { field: 'dns.question.name' } }, + dns_bytes_in: { sum: { field: 'source.bytes' } }, + dns_bytes_out: { sum: { field: 'destination.bytes' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:00:43.249Z', - lte: '2020-09-14T09:00:43.249Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:00:43.249Z', + lte: '2020-09-14T09:00:43.249Z', + format: 'strict_date_optional_time', }, }, - ], - must_not: [{ term: { 'dns.question.type': { value: 'PTR' } } }], - }, + }, + ], + must_not: [{ term: { 'dns.question.type': { value: 'PTR' } } }], }, - _source: false, - fields: [ - 'dns.question.registered_domain', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'dns.question.registered_domain', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/query.dns_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/query.dns_network.dsl.ts index cce16d8a7e5bc..12dde6681e361 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/query.dns_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/dns/query.dns_network.dsl.ts @@ -83,56 +83,54 @@ export const buildDnsQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: { - ...getCountAgg(), - dns_name_query_count: { - terms: { - field: stackByField, - size: HUGE_QUERY_SIZE, - }, - aggs: { + aggregations: { + ...getCountAgg(), + dns_name_query_count: { + terms: { + field: stackByField, + size: HUGE_QUERY_SIZE, + }, + aggs: { + bucket_sort: { bucket_sort: { - bucket_sort: { - sort: [getQueryOrder(sort), { _key: { order: Direction.asc } }], - from: cursorStart, - size: querySize, - }, + sort: [getQueryOrder(sort), { _key: { order: Direction.asc } }], + from: cursorStart, + size: querySize, }, - unique_domains: { - cardinality: { - field: 'dns.question.name', - }, + }, + unique_domains: { + cardinality: { + field: 'dns.question.name', }, - dns_bytes_in: { - sum: { - field: 'source.bytes', - }, + }, + dns_bytes_in: { + sum: { + field: 'source.bytes', }, - dns_bytes_out: { - sum: { - field: 'destination.bytes', - }, + }, + dns_bytes_out: { + sum: { + field: 'destination.bytes', }, }, }, }, - query: { - bool: { - filter, - ...createIncludePTRFilter(isPtrIncluded), - }, + }, + query: { + bool: { + filter, + ...createIncludePTRFilter(isPtrIncluded), }, - _source: false, - fields: [ - 'dns.question.registered_domain', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'dns.question.registered_domain', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/__mocks__/index.ts index 0faee60330afc..480c7a0fc1f37 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/__mocks__/index.ts @@ -628,53 +628,51 @@ export const formattedSearchStrategyResponse = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - http_count: { cardinality: { field: 'url.path' } }, - url: { - terms: { field: 'url.path', size: 10, order: { _count: 'desc' } }, - aggs: { - methods: { terms: { field: 'http.request.method', size: 4 } }, - domains: { terms: { field: 'url.domain', size: 4 } }, - status: { terms: { field: 'http.response.status_code', size: 4 } }, - source: { - top_hits: { size: 1, _source: false }, - }, + aggregations: { + http_count: { cardinality: { field: 'url.path' } }, + url: { + terms: { field: 'url.path', size: 10, order: { _count: 'desc' } }, + aggs: { + methods: { terms: { field: 'http.request.method', size: 4 } }, + domains: { terms: { field: 'url.domain', size: 4 } }, + status: { terms: { field: 'http.response.status_code', size: 4 } }, + source: { + top_hits: { size: 1, _source: false }, }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:00:43.249Z', - lte: '2020-09-14T09:00:43.249Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:00:43.249Z', + lte: '2020-09-14T09:00:43.249Z', + format: 'strict_date_optional_time', }, }, - { exists: { field: 'http.request.method' } }, - ], - }, + }, + { exists: { field: 'http.request.method' } }, + ], }, - _source: false, - fields: [ - 'host.name', - 'source.ip', - 'url.path', - 'http.request.method', - 'url.domain', - 'http.response.status_code', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'host.name', + 'source.ip', + 'url.path', + 'http.request.method', + 'url.domain', + 'http.response.status_code', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }, null, @@ -699,50 +697,48 @@ export const expectedDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - http_count: { cardinality: { field: 'url.path' } }, - url: { - terms: { field: 'url.path', size: 10, order: { _count: 'desc' } }, - aggs: { - methods: { terms: { field: 'http.request.method', size: 4 } }, - domains: { terms: { field: 'url.domain', size: 4 } }, - status: { terms: { field: 'http.response.status_code', size: 4 } }, - source: { top_hits: { size: 1, _source: false } }, - }, + aggregations: { + http_count: { cardinality: { field: 'url.path' } }, + url: { + terms: { field: 'url.path', size: 10, order: { _count: 'desc' } }, + aggs: { + methods: { terms: { field: 'http.request.method', size: 4 } }, + domains: { terms: { field: 'url.domain', size: 4 } }, + status: { terms: { field: 'http.response.status_code', size: 4 } }, + source: { top_hits: { size: 1, _source: false } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:00:43.249Z', - lte: '2020-09-14T09:00:43.249Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:00:43.249Z', + lte: '2020-09-14T09:00:43.249Z', + format: 'strict_date_optional_time', }, }, - { exists: { field: 'http.request.method' } }, - ], - }, + }, + { exists: { field: 'http.request.method' } }, + ], }, - _source: false, - fields: [ - 'host.name', - 'source.ip', - 'url.path', - 'http.request.method', - 'url.domain', - 'http.response.status_code', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'host.name', + 'source.ip', + 'url.path', + 'http.request.method', + 'url.domain', + 'http.response.status_code', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/query.http_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/query.http_network.dsl.ts index 91b036bfcabb9..ba1fd4569c283 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/query.http_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/http/query.http_network.dsl.ts @@ -40,48 +40,46 @@ export const buildHttpQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: { - ...getCountAgg(), - ...getHttpAggs(sort, querySize), - }, - query: { - bool: ip - ? { - filter, - should: [ - { - term: { - 'source.ip': ip, - }, + aggregations: { + ...getCountAgg(), + ...getHttpAggs(sort, querySize), + }, + query: { + bool: ip + ? { + filter, + should: [ + { + term: { + 'source.ip': ip, }, - { - term: { - 'destination.ip': ip, - }, + }, + { + term: { + 'destination.ip': ip, }, - ], - minimum_should_match: 1, - } - : { - filter, - }, - }, - _source: false, - fields: [ - 'host.name', - 'source.ip', - 'url.path', - 'http.request.method', - 'url.domain', - 'http.response.status_code', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, + }, + ], + minimum_should_match: 1, + } + : { + filter, + }, }, + _source: false, + fields: [ + 'host.name', + 'source.ip', + 'url.path', + 'http.request.method', + 'url.domain', + 'http.response.status_code', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/__mocks__/index.ts index 5a57a080b1e53..d20cf82bdb352 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/__mocks__/index.ts @@ -112,78 +112,76 @@ export const formattedSearchStrategyResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - unique_flow_count: { filter: { term: { type: 'flow' } } }, - unique_dns_count: { filter: { term: { type: 'dns' } } }, - unique_suricata_count: { filter: { term: { 'service.type': 'suricata' } } }, - unique_zeek_count: { filter: { term: { 'service.type': 'zeek' } } }, - unique_socket_count: { filter: { term: { 'event.dataset': 'socket' } } }, - unique_filebeat_count: { - filter: { term: { 'agent.type': 'filebeat' } }, - aggs: { - unique_netflow_count: { filter: { term: { 'input.type': 'netflow' } } }, - unique_panw_count: { filter: { term: { 'event.module': 'panw' } } }, - unique_cisco_count: { filter: { term: { 'event.module': 'cisco' } } }, - }, - }, - unique_packetbeat_count: { - filter: { term: { 'agent.type': 'packetbeat' } }, - aggs: { unique_tls_count: { filter: { term: { 'network.protocol': 'tls' } } } }, + aggregations: { + unique_flow_count: { filter: { term: { type: 'flow' } } }, + unique_dns_count: { filter: { term: { type: 'dns' } } }, + unique_suricata_count: { filter: { term: { 'service.type': 'suricata' } } }, + unique_zeek_count: { filter: { term: { 'service.type': 'zeek' } } }, + unique_socket_count: { filter: { term: { 'event.dataset': 'socket' } } }, + unique_filebeat_count: { + filter: { term: { 'agent.type': 'filebeat' } }, + aggs: { + unique_netflow_count: { filter: { term: { 'input.type': 'netflow' } } }, + unique_panw_count: { filter: { term: { 'event.module': 'panw' } } }, + unique_cisco_count: { filter: { term: { 'event.module': 'cisco' } } }, }, }, - query: { - bool: { - filter: [ - { - bool: { - must: [], - filter: [ - { match_all: {} }, - { - bool: { - filter: [ - { - bool: { - should: [ - { - bool: { - should: [{ exists: { field: 'source.ip' } }], - minimum_should_match: 1, - }, + unique_packetbeat_count: { + filter: { term: { 'agent.type': 'packetbeat' } }, + aggs: { unique_tls_count: { filter: { term: { 'network.protocol': 'tls' } } } }, + }, + }, + query: { + bool: { + filter: [ + { + bool: { + must: [], + filter: [ + { match_all: {} }, + { + bool: { + filter: [ + { + bool: { + should: [ + { + bool: { + should: [{ exists: { field: 'source.ip' } }], + minimum_should_match: 1, }, - { - bool: { - should: [{ exists: { field: 'destination.ip' } }], - minimum_should_match: 1, - }, + }, + { + bool: { + should: [{ exists: { field: 'destination.ip' } }], + minimum_should_match: 1, }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, - ], - }, + }, + ], }, - ], - should: [], - must_not: [], - }, - }, - { - range: { - '@timestamp': { - gte: '2020-09-13T12:54:24.685Z', - lte: '2020-09-14T12:54:24.685Z', - format: 'strict_date_optional_time', }, + ], + should: [], + must_not: [], + }, + }, + { + range: { + '@timestamp': { + gte: '2020-09-13T12:54:24.685Z', + lte: '2020-09-14T12:54:24.685Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, }, null, 2 @@ -216,85 +214,83 @@ export const expectedDsl = { 'packetbeat-*', 'winlogbeat-*', ], - body: { - aggregations: { - unique_flow_count: { - filter: { - term: { - type: 'flow', - }, + aggregations: { + unique_flow_count: { + filter: { + term: { + type: 'flow', }, }, - unique_dns_count: { - filter: { - term: { - type: 'dns', - }, + }, + unique_dns_count: { + filter: { + term: { + type: 'dns', }, }, - unique_suricata_count: { - filter: { - term: { - 'service.type': 'suricata', - }, + }, + unique_suricata_count: { + filter: { + term: { + 'service.type': 'suricata', }, }, - unique_zeek_count: { - filter: { - term: { - 'service.type': 'zeek', - }, + }, + unique_zeek_count: { + filter: { + term: { + 'service.type': 'zeek', }, }, - unique_socket_count: { - filter: { - term: { - 'event.dataset': 'socket', - }, + }, + unique_socket_count: { + filter: { + term: { + 'event.dataset': 'socket', }, }, - unique_filebeat_count: { - filter: { - term: { - 'agent.type': 'filebeat', - }, + }, + unique_filebeat_count: { + filter: { + term: { + 'agent.type': 'filebeat', }, - aggs: { - unique_netflow_count: { - filter: { - term: { - 'input.type': 'netflow', - }, + }, + aggs: { + unique_netflow_count: { + filter: { + term: { + 'input.type': 'netflow', }, }, - unique_panw_count: { - filter: { - term: { - 'event.module': 'panw', - }, + }, + unique_panw_count: { + filter: { + term: { + 'event.module': 'panw', }, }, - unique_cisco_count: { - filter: { - term: { - 'event.module': 'cisco', - }, + }, + unique_cisco_count: { + filter: { + term: { + 'event.module': 'cisco', }, }, }, }, - unique_packetbeat_count: { - filter: { - term: { - 'agent.type': 'packetbeat', - }, + }, + unique_packetbeat_count: { + filter: { + term: { + 'agent.type': 'packetbeat', }, - aggs: { - unique_tls_count: { - filter: { - term: { - 'network.protocol': 'tls', - }, + }, + aggs: { + unique_tls_count: { + filter: { + term: { + 'network.protocol': 'tls', }, }, }, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/query.overview_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/query.overview_network.dsl.ts index 8c1c7473d9ec2..cd680aa875616 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/query.overview_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/overview/query.overview_network.dsl.ts @@ -32,75 +32,73 @@ export const buildOverviewNetworkQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - unique_flow_count: { - filter: { - term: { type: 'flow' }, - }, + aggregations: { + unique_flow_count: { + filter: { + term: { type: 'flow' }, }, - unique_dns_count: { - filter: { - term: { type: 'dns' }, - }, + }, + unique_dns_count: { + filter: { + term: { type: 'dns' }, }, - unique_suricata_count: { - filter: { - term: { 'service.type': 'suricata' }, - }, + }, + unique_suricata_count: { + filter: { + term: { 'service.type': 'suricata' }, }, - unique_zeek_count: { - filter: { - term: { 'service.type': 'zeek' }, - }, + }, + unique_zeek_count: { + filter: { + term: { 'service.type': 'zeek' }, }, - unique_socket_count: { - filter: { - term: { 'event.dataset': 'socket' }, - }, + }, + unique_socket_count: { + filter: { + term: { 'event.dataset': 'socket' }, }, - unique_filebeat_count: { - filter: { - term: { 'agent.type': 'filebeat' }, - }, - aggs: { - unique_netflow_count: { - filter: { - term: { 'input.type': 'netflow' }, - }, + }, + unique_filebeat_count: { + filter: { + term: { 'agent.type': 'filebeat' }, + }, + aggs: { + unique_netflow_count: { + filter: { + term: { 'input.type': 'netflow' }, }, - unique_panw_count: { - filter: { - term: { 'event.module': 'panw' }, - }, + }, + unique_panw_count: { + filter: { + term: { 'event.module': 'panw' }, }, - unique_cisco_count: { - filter: { - term: { 'event.module': 'cisco' }, - }, + }, + unique_cisco_count: { + filter: { + term: { 'event.module': 'cisco' }, }, }, }, - unique_packetbeat_count: { - filter: { - term: { 'agent.type': 'packetbeat' }, - }, - aggs: { - unique_tls_count: { - filter: { - term: { 'network.protocol': 'tls' }, - }, + }, + unique_packetbeat_count: { + filter: { + term: { 'agent.type': 'packetbeat' }, + }, + aggs: { + unique_tls_count: { + filter: { + term: { 'network.protocol': 'tls' }, }, }, }, }, - query: { - bool: { - filter, - }, + }, + query: { + bool: { + filter, }, - size: 0, }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/__mocks__/index.ts index b3052b45ed223..0ae27cccd4aea 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/__mocks__/index.ts @@ -72,37 +72,35 @@ export const formattedSearchStrategyResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - count: { cardinality: { field: 'tls.server.hash.sha1' } }, - sha1: { - terms: { field: 'tls.server.hash.sha1', size: 10, order: { _key: 'desc' } }, - aggs: { - issuers: { terms: { field: 'tls.server.issuer' } }, - subjects: { terms: { field: 'tls.server.subject' } }, - not_after: { terms: { field: 'tls.server.not_after' } }, - ja3: { terms: { field: 'tls.client.ja3' } }, - }, + aggs: { + count: { cardinality: { field: 'tls.server.hash.sha1' } }, + sha1: { + terms: { field: 'tls.server.hash.sha1', size: 10, order: { _key: 'desc' } }, + aggs: { + issuers: { terms: { field: 'tls.server.issuer' } }, + subjects: { terms: { field: 'tls.server.subject' } }, + not_after: { terms: { field: 'tls.server.not_after' } }, + ja3: { terms: { field: 'tls.client.ja3' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:58:58.637Z', - lte: '2020-09-14T09:58:58.637Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:58:58.637Z', + lte: '2020-09-14T09:58:58.637Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, }, null, 2 @@ -127,35 +125,33 @@ export const expectedDsl = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - count: { cardinality: { field: 'tls.server.hash.sha1' } }, - sha1: { - terms: { field: 'tls.server.hash.sha1', size: 10, order: { _key: 'desc' } }, - aggs: { - issuers: { terms: { field: 'tls.server.issuer' } }, - subjects: { terms: { field: 'tls.server.subject' } }, - not_after: { terms: { field: 'tls.server.not_after' } }, - ja3: { terms: { field: 'tls.client.ja3' } }, - }, + aggs: { + count: { cardinality: { field: 'tls.server.hash.sha1' } }, + sha1: { + terms: { field: 'tls.server.hash.sha1', size: 10, order: { _key: 'desc' } }, + aggs: { + issuers: { terms: { field: 'tls.server.issuer' } }, + subjects: { terms: { field: 'tls.server.subject' } }, + not_after: { terms: { field: 'tls.server.not_after' } }, + ja3: { terms: { field: 'tls.client.ja3' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:58:58.637Z', - lte: '2020-09-14T09:58:58.637Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:58:58.637Z', + lte: '2020-09-14T09:58:58.637Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/query.tls_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/query.tls_network.dsl.ts index faa07bd770fa2..01e40da4e25d6 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/query.tls_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/tls/query.tls_network.dsl.ts @@ -76,17 +76,15 @@ export const buildNetworkTlsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - ...getAggs(querySize, sort), - }, - query: { - bool: { - filter, - }, + aggs: { + ...getAggs(querySize, sort), + }, + query: { + bool: { + filter, }, - size: 0, }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/__mocks__/index.ts index dfbc1067733bd..80a0e9d0e07a5 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/__mocks__/index.ts @@ -70,42 +70,40 @@ export const formattedSearchStrategyResponse = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - top_countries_count: { cardinality: { field: 'destination.geo.country_iso_code' } }, - destination: { - terms: { - field: 'destination.geo.country_iso_code', - size: 10, - order: { bytes_in: 'desc' }, - }, - aggs: { - bytes_in: { sum: { field: 'source.bytes' } }, - bytes_out: { sum: { field: 'destination.bytes' } }, - flows: { cardinality: { field: 'network.community_id' } }, - source_ips: { cardinality: { field: 'source.ip' } }, - destination_ips: { cardinality: { field: 'destination.ip' } }, - }, + aggregations: { + top_countries_count: { cardinality: { field: 'destination.geo.country_iso_code' } }, + destination: { + terms: { + field: 'destination.geo.country_iso_code', + size: 10, + order: { bytes_in: 'desc' }, + }, + aggs: { + bytes_in: { sum: { field: 'source.bytes' } }, + bytes_out: { sum: { field: 'destination.bytes' } }, + flows: { cardinality: { field: 'network.community_id' } }, + source_ips: { cardinality: { field: 'source.ip' } }, + destination_ips: { cardinality: { field: 'destination.ip' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:58:58.637Z', - lte: '2020-09-14T09:58:58.637Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:58:58.637Z', + lte: '2020-09-14T09:58:58.637Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, track_total_hits: false, }, null, @@ -130,37 +128,35 @@ export const expectedDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - top_countries_count: { cardinality: { field: 'destination.geo.country_iso_code' } }, - destination: { - terms: { field: 'destination.geo.country_iso_code', size: 10, order: { bytes_in: 'desc' } }, - aggs: { - bytes_in: { sum: { field: 'source.bytes' } }, - bytes_out: { sum: { field: 'destination.bytes' } }, - flows: { cardinality: { field: 'network.community_id' } }, - source_ips: { cardinality: { field: 'source.ip' } }, - destination_ips: { cardinality: { field: 'destination.ip' } }, - }, + aggregations: { + top_countries_count: { cardinality: { field: 'destination.geo.country_iso_code' } }, + destination: { + terms: { field: 'destination.geo.country_iso_code', size: 10, order: { bytes_in: 'desc' } }, + aggs: { + bytes_in: { sum: { field: 'source.bytes' } }, + bytes_out: { sum: { field: 'destination.bytes' } }, + flows: { cardinality: { field: 'network.community_id' } }, + source_ips: { cardinality: { field: 'source.ip' } }, + destination_ips: { cardinality: { field: 'destination.ip' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T09:58:58.637Z', - lte: '2020-09-14T09:58:58.637Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T09:58:58.637Z', + lte: '2020-09-14T09:58:58.637Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/query.top_countries_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/query.top_countries_network.dsl.ts index 501e8122d50e0..bf7d5e2875775 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/query.top_countries_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_countries/query.top_countries_network.dsl.ts @@ -44,30 +44,28 @@ export const buildTopCountriesQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: { - ...getCountAgg(flowTarget), - ...getFlowTargetAggs(sort, flowTarget, querySize), - }, - query: { - bool: ip - ? { - filter, - should: [ - { - term: { - [`${getOppositeField(flowTarget)}.ip`]: ip, - }, + aggregations: { + ...getCountAgg(flowTarget), + ...getFlowTargetAggs(sort, flowTarget, querySize), + }, + query: { + bool: ip + ? { + filter, + should: [ + { + term: { + [`${getOppositeField(flowTarget)}.ip`]: ip, }, - ], - minimum_should_match: 1, - } - : { - filter, - }, - }, - size: 0, + }, + ], + minimum_should_match: 1, + } + : { + filter, + }, }, + size: 0, track_total_hits: false, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/__mocks__/index.ts index b6061714b6597..31eef894f694c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/__mocks__/index.ts @@ -872,83 +872,81 @@ export const formattedSearchStrategyResponse: NetworkTopNFlowStrategyResponse = 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - source: { - terms: { field: 'source.ip', size: 10, order: { bytes_out: 'desc' } }, - aggs: { - bytes_in: { sum: { field: 'destination.bytes' } }, - bytes_out: { sum: { field: 'source.bytes' } }, - domain: { - terms: { field: 'source.domain', order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - location: { - filter: { exists: { field: 'source.geo' } }, - aggs: { - top_geo: { - top_hits: { - _source: false, - fields: [ - 'source.geo.*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - }, + aggregations: { + source: { + terms: { field: 'source.ip', size: 10, order: { bytes_out: 'desc' } }, + aggs: { + bytes_in: { sum: { field: 'destination.bytes' } }, + bytes_out: { sum: { field: 'source.bytes' } }, + domain: { + terms: { field: 'source.domain', order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + location: { + filter: { exists: { field: 'source.geo' } }, + aggs: { + top_geo: { + top_hits: { + _source: false, + fields: [ + 'source.geo.*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, }, }, }, - autonomous_system: { - filter: { exists: { field: 'source.as' } }, - aggs: { - top_as: { - top_hits: { - _source: false, - fields: [ - 'source.as.*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - }, + }, + autonomous_system: { + filter: { exists: { field: 'source.as' } }, + aggs: { + top_as: { + top_hits: { + _source: false, + fields: [ + 'source.as.*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, }, }, }, - flows: { cardinality: { field: 'network.community_id' } }, - destination_ips: { cardinality: { field: 'destination.ip' } }, }, + flows: { cardinality: { field: 'network.community_id' } }, + destination_ips: { cardinality: { field: 'destination.ip' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T10:16:46.870Z', - lte: '2020-09-14T10:16:46.870Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T10:16:46.870Z', + lte: '2020-09-14T10:16:46.870Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }, null, @@ -976,29 +974,27 @@ export const formattedCountStrategyResponse: NetworkTopNFlowCountStrategyRespons 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - top_n_flow_count: { cardinality: { field: 'source.ip' } }, - }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T10:16:46.870Z', - lte: '2020-09-14T10:16:46.870Z', - format: 'strict_date_optional_time', - }, + aggregations: { + top_n_flow_count: { cardinality: { field: 'source.ip' } }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T10:16:46.870Z', + lte: '2020-09-14T10:16:46.870Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, - size: 0, }, + _source: false, + size: 0, track_total_hits: false, }, null, @@ -1023,83 +1019,81 @@ export const expectedDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - source: { - terms: { field: 'source.ip', size: 10, order: { bytes_out: 'desc' } }, - aggs: { - bytes_in: { sum: { field: 'destination.bytes' } }, - bytes_out: { sum: { field: 'source.bytes' } }, - domain: { - terms: { field: 'source.domain', order: { timestamp: 'desc' } }, - aggs: { timestamp: { max: { field: '@timestamp' } } }, - }, - location: { - filter: { exists: { field: 'source.geo' } }, - aggs: { - top_geo: { - top_hits: { - _source: false, - fields: [ - 'source.geo.*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - }, + aggregations: { + source: { + terms: { field: 'source.ip', size: 10, order: { bytes_out: 'desc' } }, + aggs: { + bytes_in: { sum: { field: 'destination.bytes' } }, + bytes_out: { sum: { field: 'source.bytes' } }, + domain: { + terms: { field: 'source.domain', order: { timestamp: 'desc' } }, + aggs: { timestamp: { max: { field: '@timestamp' } } }, + }, + location: { + filter: { exists: { field: 'source.geo' } }, + aggs: { + top_geo: { + top_hits: { + _source: false, + fields: [ + 'source.geo.*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, }, }, }, - autonomous_system: { - filter: { exists: { field: 'source.as' } }, - aggs: { - top_as: { - top_hits: { - _source: false, - fields: [ - 'source.as.*', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 1, - }, + }, + autonomous_system: { + filter: { exists: { field: 'source.as' } }, + aggs: { + top_as: { + top_hits: { + _source: false, + fields: [ + 'source.as.*', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 1, }, }, }, - flows: { cardinality: { field: 'network.community_id' } }, - destination_ips: { cardinality: { field: 'destination.ip' } }, }, + flows: { cardinality: { field: 'network.community_id' } }, + destination_ips: { cardinality: { field: 'destination.ip' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T10:16:46.870Z', - lte: '2020-09-14T10:16:46.870Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T10:16:46.870Z', + lte: '2020-09-14T10:16:46.870Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; @@ -1116,28 +1110,26 @@ export const expectedCountDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - top_n_flow_count: { cardinality: { field: 'source.ip' } }, - }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T10:16:46.870Z', - lte: '2020-09-14T10:16:46.870Z', - format: 'strict_date_optional_time', - }, + aggregations: { + top_n_flow_count: { cardinality: { field: 'source.ip' } }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T10:16:46.870Z', + lte: '2020-09-14T10:16:46.870Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, - size: 0, }, + _source: false, + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts index 0bda64f6aaf0e..6c57c67eda0cf 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts @@ -46,18 +46,16 @@ export const buildTopNFlowQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: getFlowTargetAggs(sort, flowTarget, querySize), - query, - _source: false, - fields: [ - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, - }, + aggregations: getFlowTargetAggs(sort, flowTarget, querySize), + query, + _source: false, + fields: [ + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; return dslQuery; @@ -75,12 +73,10 @@ export const buildTopNFlowCountQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: getCountAgg(flowTarget), - query, - _source: false, - size: 0, - }, + aggregations: getCountAgg(flowTarget), + query, + _source: false, + size: 0, track_total_hits: false, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/__mocks__/index.ts index a61dd74ce68f8..da0f51839b02c 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/__mocks__/index.ts @@ -132,38 +132,36 @@ export const formattedSearchStrategyResponse = { ], ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - user_count: { cardinality: { field: 'user.name' } }, - users: { - terms: { field: 'user.name', size: 10, order: { _key: 'asc' } }, - aggs: { - id: { terms: { field: 'user.id' } }, - groupId: { terms: { field: 'user.group.id' } }, - groupName: { terms: { field: 'user.group.name' } }, - }, + aggs: { + user_count: { cardinality: { field: 'user.name' } }, + users: { + terms: { field: 'user.name', size: 10, order: { _key: 'asc' } }, + aggs: { + id: { terms: { field: 'user.id' } }, + groupId: { terms: { field: 'user.group.id' } }, + groupName: { terms: { field: 'user.group.name' } }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - gte: '2020-09-13T10:16:46.870Z', - lte: '2020-09-14T10:16:46.870Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + gte: '2020-09-13T10:16:46.870Z', + lte: '2020-09-14T10:16:46.870Z', + format: 'strict_date_optional_time', }, }, - { term: { 'source.ip': '10.142.0.7' } }, - ], - must_not: [{ term: { 'event.category': 'authentication' } }], - }, + }, + { term: { 'source.ip': '10.142.0.7' } }, + ], + must_not: [{ term: { 'event.category': 'authentication' } }], }, - size: 0, }, + size: 0, }, null, 2 @@ -177,38 +175,36 @@ export const formattedSearchStrategyResponse = { export const expectedDsl = { allow_no_indices: true, track_total_hits: false, - body: { - aggs: { - user_count: { cardinality: { field: 'user.name' } }, - users: { - aggs: { - groupId: { terms: { field: 'user.group.id' } }, - groupName: { terms: { field: 'user.group.name' } }, - id: { terms: { field: 'user.id' } }, - }, - terms: { field: 'user.name', order: { _key: 'asc' }, size: 10 }, + aggs: { + user_count: { cardinality: { field: 'user.name' } }, + users: { + aggs: { + groupId: { terms: { field: 'user.group.id' } }, + groupName: { terms: { field: 'user.group.name' } }, + id: { terms: { field: 'user.id' } }, }, + terms: { field: 'user.name', order: { _key: 'asc' }, size: 10 }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gte: '2020-09-13T10:16:46.870Z', - lte: '2020-09-14T10:16:46.870Z', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gte: '2020-09-13T10:16:46.870Z', + lte: '2020-09-14T10:16:46.870Z', }, }, - { term: { 'source.ip': '10.142.0.7' } }, - ], - must_not: [{ term: { 'event.category': 'authentication' } }], - }, + }, + { term: { 'source.ip': '10.142.0.7' } }, + ], + must_not: [{ term: { 'event.category': 'authentication' } }], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: [ 'apm-*-transaction*', diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/query.users_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/query.users_network.dsl.ts index 3f3135d379d80..7e3a89fdbff40 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/query.users_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/users/query.users_network.dsl.ts @@ -37,54 +37,52 @@ export const buildUsersQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - user_count: { - cardinality: { - field: 'user.name', + aggs: { + user_count: { + cardinality: { + field: 'user.name', + }, + }, + users: { + terms: { + field: 'user.name', + size: querySize, + order: { + ...getQueryOrder(sort), }, }, - users: { - terms: { - field: 'user.name', - size: querySize, - order: { - ...getQueryOrder(sort), + aggs: { + id: { + terms: { + field: 'user.id', }, }, - aggs: { - id: { - terms: { - field: 'user.id', - }, + groupId: { + terms: { + field: 'user.group.id', }, - groupId: { - terms: { - field: 'user.group.id', - }, - }, - groupName: { - terms: { - field: 'user.group.name', - }, + }, + groupName: { + terms: { + field: 'user.group.name', }, }, }, }, - query: { - bool: { - filter, - must_not: [ - { - term: { - 'event.category': 'authentication', - }, + }, + query: { + bool: { + filter, + must_not: [ + { + term: { + 'event.category': 'authentication', }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/__mocks__/index.ts index ba257d7d1b51a..b0d95a9e6d2a4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/__mocks__/index.ts @@ -116,35 +116,33 @@ export const mockDeps = () => ({ export const expectedDsl = { allow_no_indices: true, track_total_hits: false, - body: { - aggregations: { - host_count: { cardinality: { field: 'host.name' } }, - host_data: { - terms: { field: 'host.name', size: 1000 }, - aggs: { - ip: { terms: { field: 'host.ip', size: 10 } }, - }, + aggregations: { + host_count: { cardinality: { field: 'host.name' } }, + host_data: { + terms: { field: 'host.name', size: 1000 }, + aggs: { + ip: { terms: { field: 'host.ip', size: 10 } }, }, }, - query: { - bool: { - filter: [ - { term: { 'user.name': 'user1' } }, - { term: { 'event.category': 'authentication' } }, - { term: { 'event.outcome': 'success' } }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gt: '2020-09-02T15:17:13.678Z', - }, + }, + query: { + bool: { + filter: [ + { term: { 'user.name': 'user1' } }, + { term: { 'event.category': 'authentication' } }, + { term: { 'event.outcome': 'success' } }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gt: '2020-09-02T15:17:13.678Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: ['test_indices*'], }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/query.related_hosts.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/query.related_hosts.dsl.ts index 7ef08545edd46..a7fadbbc65743 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/query.related_hosts.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_hosts/query.related_hosts.dsl.ts @@ -34,27 +34,25 @@ export const buildRelatedHostsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - host_count: { cardinality: { field: 'host.name' } }, - host_data: { - terms: { - field: 'host.name', - size: 1000, - }, - aggs: { - ip: { - terms: { - field: 'host.ip', - size: 10, - }, + aggregations: { + host_count: { cardinality: { field: 'host.name' } }, + host_data: { + terms: { + field: 'host.name', + size: 1000, + }, + aggs: { + ip: { + terms: { + field: 'host.ip', + size: 10, }, }, }, }, - query: { bool: { filter } }, - size: 0, }, + query: { bool: { filter } }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/__mocks__/index.ts index 3dc412b7faef1..b2dcf02e8f2f4 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/__mocks__/index.ts @@ -112,35 +112,33 @@ export const mockDeps = () => ({ export const expectedDsl = { allow_no_indices: true, track_total_hits: false, - body: { - aggregations: { - user_count: { cardinality: { field: 'user.name' } }, - user_data: { - terms: { field: 'user.name', size: 1000 }, - aggs: { - ip: { terms: { field: 'host.ip', size: 10 } }, - }, + aggregations: { + user_count: { cardinality: { field: 'user.name' } }, + user_data: { + terms: { field: 'user.name', size: 1000 }, + aggs: { + ip: { terms: { field: 'host.ip', size: 10 } }, }, }, - query: { - bool: { - filter: [ - { term: { 'host.name': 'host1' } }, - { term: { 'event.category': 'authentication' } }, - { term: { 'event.outcome': 'success' } }, - { - range: { - '@timestamp': { - format: 'strict_date_optional_time', - gt: '2020-09-02T15:17:13.678Z', - }, + }, + query: { + bool: { + filter: [ + { term: { 'host.name': 'host1' } }, + { term: { 'event.category': 'authentication' } }, + { term: { 'event.outcome': 'success' } }, + { + range: { + '@timestamp': { + format: 'strict_date_optional_time', + gt: '2020-09-02T15:17:13.678Z', }, }, - ], - }, + }, + ], }, - size: 0, }, + size: 0, ignore_unavailable: true, index: ['test_indices*'], }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/query.related_users.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/query.related_users.dsl.ts index dae897684d6b6..cf857b9ccc2db 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/query.related_users.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/related_entities/related_users/query.related_users.dsl.ts @@ -34,27 +34,25 @@ export const buildRelatedUsersQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - user_count: { cardinality: { field: 'user.name' } }, - user_data: { - terms: { - field: 'user.name', - size: 1000, - }, - aggs: { - ip: { - terms: { - field: 'host.ip', - size: 10, - }, + aggregations: { + user_count: { cardinality: { field: 'user.name' } }, + user_data: { + terms: { + field: 'user.name', + size: 1000, + }, + aggs: { + ip: { + terms: { + field: 'host.ip', + size: 10, }, }, }, }, - query: { bool: { filter } }, - size: 0, }, + query: { bool: { filter } }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/query.risk_score.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/query.risk_score.dsl.ts index 23491e2b8cd32..dd8a9d4a63d0b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/query.risk_score.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/query.risk_score.dsl.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { Sort } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { Sort } from '@elastic/elasticsearch/lib/api/types'; import { EntityTypeToIdentifierField } from '../../../../../../common/entity_analytics/types'; import type { RiskScoreRequestOptions } from '../../../../../../common/api/search_strategy'; import { Direction, RiskScoreFields } from '../../../../../../common/search_strategy'; @@ -51,10 +51,8 @@ export const buildRiskScoreQuery = ({ track_total_hits: true, size: querySize, from: cursorStart, - body: { - query: { bool: { filter } }, - sort: getQueryOrder(sort), - }, + query: { bool: { filter } }, + sort: getQueryOrder(sort), }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/query.kpi_risk_score.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/query.kpi_risk_score.dsl.ts index f397e3a14ec09..16fa401c4e6a5 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/query.kpi_risk_score.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/query.kpi_risk_score.dsl.ts @@ -35,28 +35,26 @@ export const buildKpiRiskScoreQuery = ({ allow_no_indices: false, ignore_unavailable: true, track_total_hits: false, - body: { - aggs: { - risk: { - terms: { - field: EntityTypeToLevelField[entity], - }, - aggs: { - unique_entries: { - cardinality: { - field: EntityTypeToIdentifierField[entity], - }, + aggs: { + risk: { + terms: { + field: EntityTypeToLevelField[entity], + }, + aggs: { + unique_entries: { + cardinality: { + field: EntityTypeToIdentifierField[entity], }, }, }, }, - query: { - bool: { - filter, - }, + }, + query: { + bool: { + filter, }, - size: 0, }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/index.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/index.test.ts.snap index 3b93b454c8b3d..24f2fce674dce 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/index.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/index.test.ts.snap @@ -11,226 +11,224 @@ Object { ], \\"ignore_unavailable\\": true, \\"track_total_hits\\": false, - \\"body\\": { - \\"aggregations\\": { - \\"service_id\\": { - \\"terms\\": { - \\"field\\": \\"service.id\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } - } + \\"aggregations\\": { + \\"service_id\\": { + \\"terms\\": { + \\"field\\": \\"service.id\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" } }, - \\"service_name\\": { - \\"terms\\": { - \\"field\\": \\"service.name\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_name\\": { + \\"terms\\": { + \\"field\\": \\"service.name\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_address\\": { - \\"terms\\": { - \\"field\\": \\"service.address\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_address\\": { + \\"terms\\": { + \\"field\\": \\"service.address\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_environment\\": { - \\"terms\\": { - \\"field\\": \\"service.environment\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_environment\\": { + \\"terms\\": { + \\"field\\": \\"service.environment\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_ephemeral_id\\": { - \\"terms\\": { - \\"field\\": \\"service.ephemeral_id\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_ephemeral_id\\": { + \\"terms\\": { + \\"field\\": \\"service.ephemeral_id\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_node_name\\": { - \\"terms\\": { - \\"field\\": \\"service.node.name\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_node_name\\": { + \\"terms\\": { + \\"field\\": \\"service.node.name\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_node_roles\\": { - \\"terms\\": { - \\"field\\": \\"service.node.roles\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_node_roles\\": { + \\"terms\\": { + \\"field\\": \\"service.node.roles\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_node_role\\": { - \\"terms\\": { - \\"field\\": \\"service.node.role\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_node_role\\": { + \\"terms\\": { + \\"field\\": \\"service.node.role\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_state\\": { - \\"terms\\": { - \\"field\\": \\"service.state\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_state\\": { + \\"terms\\": { + \\"field\\": \\"service.state\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_type\\": { - \\"terms\\": { - \\"field\\": \\"service.type\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"service_type\\": { + \\"terms\\": { + \\"field\\": \\"service.type\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"service_version\\": { - \\"terms\\": { - \\"field\\": \\"service.version\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } } }, - \\"query\\": { - \\"bool\\": { - \\"filter\\": [ - { - \\"bool\\": { - \\"must\\": [], - \\"filter\\": [ - { - \\"match_all\\": {} - }, - { - \\"match_phrase\\": { - \\"service.name\\": { - \\"query\\": \\"test_service\\" - } + \\"service_version\\": { + \\"terms\\": { + \\"field\\": \\"service.version\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } + }, + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" + } + } + } + } + }, + \\"query\\": { + \\"bool\\": { + \\"filter\\": [ + { + \\"bool\\": { + \\"must\\": [], + \\"filter\\": [ + { + \\"match_all\\": {} + }, + { + \\"match_phrase\\": { + \\"service.name\\": { + \\"query\\": \\"test_service\\" } } - ], - \\"should\\": [], - \\"must_not\\": [] - } - }, - { - \\"term\\": { - \\"service.name\\": \\"bastion00.siem.estc.dev\\" - } - }, - { - \\"range\\": { - \\"@timestamp\\": { - \\"format\\": \\"strict_date_optional_time\\", - \\"gte\\": \\"2020-09-02T15:17:13.678Z\\", - \\"lte\\": \\"2020-09-03T15:17:13.678Z\\" } + ], + \\"should\\": [], + \\"must_not\\": [] + } + }, + { + \\"term\\": { + \\"service.name\\": \\"bastion00.siem.estc.dev\\" + } + }, + { + \\"range\\": { + \\"@timestamp\\": { + \\"format\\": \\"strict_date_optional_time\\", + \\"gte\\": \\"2020-09-02T15:17:13.678Z\\", + \\"lte\\": \\"2020-09-03T15:17:13.678Z\\" } } - ] - } - }, - \\"size\\": 0 - } + } + ] + } + }, + \\"size\\": 0 }", ], }, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/query.observed_service_details.dsl.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/query.observed_service_details.dsl.test.ts.snap index 1933022563dd8..01e2f4b1658b5 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/query.observed_service_details.dsl.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/__snapshots__/query.observed_service_details.dsl.test.ts.snap @@ -2,231 +2,229 @@ exports[`buildServiceDetailsQuery build query from options correctly 1`] = ` Object { - "allow_no_indices": true, - "body": Object { - "aggregations": Object { - "service_address": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + "aggregations": Object { + "service_address": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.address", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.address", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_environment": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_environment": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.environment", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.environment", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_ephemeral_id": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_ephemeral_id": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.ephemeral_id", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.ephemeral_id", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_id": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_id": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.id", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.id", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_name": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_name": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.name", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.name", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_node_name": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_node_name": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.node.name", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.node.name", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_node_role": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_node_role": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.node.role", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.node.role", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_node_roles": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_node_roles": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.node.roles", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.node.roles", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_state": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_state": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.state", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.state", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_type": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_type": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.type", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.type", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "service_version": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "service_version": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "service.version", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "service.version", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "match_all": Object {}, - }, - Object { - "match_phrase": Object { - "service.name": Object { - "query": "test_service", - }, + }, + "allow_no_indices": true, + "ignore_unavailable": true, + "index": Array [ + "test_indices*", + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "match_all": Object {}, + }, + Object { + "match_phrase": Object { + "service.name": Object { + "query": "test_service", }, }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], }, - Object { - "term": Object { - "service.name": "bastion00.siem.estc.dev", - }, + }, + Object { + "term": Object { + "service.name": "bastion00.siem.estc.dev", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "strict_date_optional_time", - "gte": "2020-09-02T15:17:13.678Z", - "lte": "2020-09-03T15:17:13.678Z", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "strict_date_optional_time", + "gte": "2020-09-02T15:17:13.678Z", + "lte": "2020-09-03T15:17:13.678Z", }, }, - ], - }, + }, + ], }, - "size": 0, }, - "ignore_unavailable": true, - "index": Array [ - "test_indices*", - ], + "size": 0, "track_total_hits": false, } `; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/query.observed_service_details.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/query.observed_service_details.dsl.ts index 67155afe78c82..4fa892cfeb38b 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/query.observed_service_details.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/services/observed_details/query.observed_service_details.dsl.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ISearchRequestParams } from '@kbn/search-types'; import type { ObservedServiceDetailsRequestOptions } from '../../../../../../common/api/search_strategy'; import { createQueryFilterClauses } from '../../../../../utils/build_query'; @@ -37,13 +37,11 @@ export const buildObservedServiceDetailsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - ...buildFieldsTermAggregation(SERVICE_FIELDS), - }, - query: { bool: { filter } }, - size: 0, + aggregations: { + ...buildFieldsTermAggregation(SERVICE_FIELDS), }, + query: { bool: { filter } }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/__snapshots__/query.all_users.dsl.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/__snapshots__/query.all_users.dsl.test.ts.snap index 2b661fe355a13..16a135c3b6513 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/__snapshots__/query.all_users.dsl.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/__snapshots__/query.all_users.dsl.test.ts.snap @@ -2,93 +2,91 @@ exports[`buildUsersQuery build query from options correctly 1`] = ` Object { - "allow_no_indices": true, - "body": Object { - "_source": false, - "aggregations": Object { - "user_count": Object { - "cardinality": Object { - "field": "user.name", - }, + "_source": false, + "aggregations": Object { + "user_count": Object { + "cardinality": Object { + "field": "user.name", }, - "user_data": Object { - "aggs": Object { - "domain": Object { - "top_hits": Object { - "_source": false, - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, + }, + "user_data": Object { + "aggs": Object { + "domain": Object { + "top_hits": Object { + "_source": false, + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", }, - ], - }, - }, - "lastSeen": Object { - "max": Object { - "field": "@timestamp", - }, + }, + ], }, }, - "terms": Object { - "field": "user.name", - "order": Object { - "_key": "asc", + "lastSeen": Object { + "max": Object { + "field": "@timestamp", }, - "size": 10, }, }, - }, - "fields": Array [ - "user.name", - "user.domain", - Object { - "field": "@timestamp", - "format": "strict_date_optional_time", + "terms": Object { + "field": "user.name", + "order": Object { + "_key": "asc", + }, + "size": 10, }, - ], - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "match_all": Object {}, - }, - Object { - "match_phrase": Object { - "user.name": Object { - "query": "test_user", - }, + }, + }, + "allow_no_indices": true, + "fields": Array [ + "user.name", + "user.domain", + Object { + "field": "@timestamp", + "format": "strict_date_optional_time", + }, + ], + "ignore_unavailable": true, + "index": Array [ + "test_indices*", + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "match_all": Object {}, + }, + Object { + "match_phrase": Object { + "user.name": Object { + "query": "test_user", }, }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "format": "strict_date_optional_time", - "gte": "2020-09-02T15:17:13.678Z", - "lte": "2020-09-03T15:17:13.678Z", }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "strict_date_optional_time", + "gte": "2020-09-02T15:17:13.678Z", + "lte": "2020-09-03T15:17:13.678Z", }, }, - ], - }, + }, + ], }, - "size": 0, }, - "ignore_unavailable": true, - "index": Array [ - "test_indices*", - ], + "size": 0, "track_total_hits": false, } `; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/query.all_users.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/query.all_users.dsl.ts index b61f31cff4671..934b5232cdd06 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/query.all_users.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/query.all_users.dsl.ts @@ -40,41 +40,39 @@ export const buildUsersQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - user_count: { cardinality: { field: 'user.name' } }, - user_data: { - terms: { size: querySize, field: 'user.name', order: getQueryOrder(sort) }, - aggs: { - lastSeen: { max: { field: '@timestamp' } }, - domain: { - top_hits: { - size: 1, - sort: [ - { - '@timestamp': { - order: 'desc' as const, - }, + aggregations: { + user_count: { cardinality: { field: 'user.name' } }, + user_data: { + terms: { size: querySize, field: 'user.name', order: getQueryOrder(sort) }, + aggs: { + lastSeen: { max: { field: '@timestamp' } }, + domain: { + top_hits: { + size: 1, + sort: [ + { + '@timestamp': { + order: 'desc' as const, }, - ], - _source: false, - }, + }, + ], + _source: false, }, }, }, }, - query: { bool: { filter } }, - _source: false, - fields: [ - 'user.name', - 'user.domain', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + query: { bool: { filter } }, + _source: false, + fields: [ + 'user.name', + 'user.domain', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/__mocks__/index.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/__mocks__/index.ts index ca1530258d031..5c407531be960 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/__mocks__/index.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/__mocks__/index.ts @@ -716,72 +716,70 @@ export const formattedSearchStrategyResponse = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - stack_by_count: { cardinality: { field: 'user.name' } }, - stack_by: { - terms: { - size: 10, - field: 'user.name', - order: [{ 'successes.doc_count': 'desc' }, { 'failures.doc_count': 'desc' }], - }, - aggs: { - failures: { - filter: { term: { 'event.outcome': 'failure' } }, - aggs: { - lastFailure: { - top_hits: { - size: 1, - _source: false, - sort: [{ '@timestamp': { order: 'desc' } }], - }, + aggregations: { + stack_by_count: { cardinality: { field: 'user.name' } }, + stack_by: { + terms: { + size: 10, + field: 'user.name', + order: [{ 'successes.doc_count': 'desc' }, { 'failures.doc_count': 'desc' }], + }, + aggs: { + failures: { + filter: { term: { 'event.outcome': 'failure' } }, + aggs: { + lastFailure: { + top_hits: { + size: 1, + _source: false, + sort: [{ '@timestamp': { order: 'desc' } }], }, }, }, - successes: { - filter: { term: { 'event.outcome': 'success' } }, - aggs: { - lastSuccess: { - top_hits: { - size: 1, - _source: false, - sort: [{ '@timestamp': { order: 'desc' } }], - }, + }, + successes: { + filter: { term: { 'event.outcome': 'success' } }, + aggs: { + lastSuccess: { + top_hits: { + size: 1, + _source: false, + sort: [{ '@timestamp': { order: 'desc' } }], }, }, }, }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { term: { 'event.category': 'authentication' } }, - { - range: { - '@timestamp': { - gte: '2020-09-02T15:17:13.678Z', - lte: '2020-09-03T15:17:13.678Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { term: { 'event.category': 'authentication' } }, + { + range: { + '@timestamp': { + gte: '2020-09-02T15:17:13.678Z', + lte: '2020-09-03T15:17:13.678Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - size: 0, - _source: false, - fields: [ - 'source.ip', - 'host.id', - 'host.name', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], }, + size: 0, + _source: false, + fields: [ + 'source.ip', + 'host.id', + 'host.name', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], track_total_hits: false, }, null, @@ -947,64 +945,62 @@ export const expectedDsl = { 'winlogbeat-*', ], ignore_unavailable: true, - body: { - aggregations: { - stack_by_count: { cardinality: { field: 'user.name' } }, - stack_by: { - terms: { - size: 10, - field: 'user.name', - order: [{ 'successes.doc_count': 'desc' }, { 'failures.doc_count': 'desc' }], - }, - aggs: { - failures: { - filter: { term: { 'event.outcome': 'failure' } }, - aggs: { - lastFailure: { - top_hits: { size: 1, _source: false, sort: [{ '@timestamp': { order: 'desc' } }] }, - }, + aggregations: { + stack_by_count: { cardinality: { field: 'user.name' } }, + stack_by: { + terms: { + size: 10, + field: 'user.name', + order: [{ 'successes.doc_count': 'desc' }, { 'failures.doc_count': 'desc' }], + }, + aggs: { + failures: { + filter: { term: { 'event.outcome': 'failure' } }, + aggs: { + lastFailure: { + top_hits: { size: 1, _source: false, sort: [{ '@timestamp': { order: 'desc' } }] }, }, }, - successes: { - filter: { term: { 'event.outcome': 'success' } }, - aggs: { - lastSuccess: { - top_hits: { size: 1, _source: false, sort: [{ '@timestamp': { order: 'desc' } }] }, - }, + }, + successes: { + filter: { term: { 'event.outcome': 'success' } }, + aggs: { + lastSuccess: { + top_hits: { size: 1, _source: false, sort: [{ '@timestamp': { order: 'desc' } }] }, }, }, }, }, }, - query: { - bool: { - filter: [ - { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, - { term: { 'event.category': 'authentication' } }, - { - range: { - '@timestamp': { - gte: '2020-09-02T15:17:13.678Z', - lte: '2020-09-03T15:17:13.678Z', - format: 'strict_date_optional_time', - }, + }, + query: { + bool: { + filter: [ + { bool: { must: [], filter: [{ match_all: {} }], should: [], must_not: [] } }, + { term: { 'event.category': 'authentication' } }, + { + range: { + '@timestamp': { + gte: '2020-09-02T15:17:13.678Z', + lte: '2020-09-03T15:17:13.678Z', + format: 'strict_date_optional_time', }, }, - ], - }, + }, + ], }, - _source: false, - fields: [ - 'source.ip', - 'host.id', - 'host.name', - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], - size: 0, }, + _source: false, + fields: [ + 'source.ip', + 'host.id', + 'host.name', + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], + size: 0, track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/dsl/query.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/dsl/query.dsl.ts index 5c10902482a50..357ea74bd341f 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/dsl/query.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/authentications/dsl/query.dsl.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { UserAuthenticationsRequestOptions } from '../../../../../../../common/api/search_strategy'; import { createQueryFilterClauses } from '../../../../../../utils/build_query'; import { authenticationsFields } from '../helpers'; @@ -36,73 +36,71 @@ export const buildQuery = ({ allow_no_indices: true, index: defaultIndex, ignore_unavailable: true, - body: { - aggregations: { - stack_by_count: { - cardinality: { - field: stackByField, - }, + aggregations: { + stack_by_count: { + cardinality: { + field: stackByField, }, - stack_by: { - terms: { - size: querySize, - field: stackByField, - order: [ - { 'successes.doc_count': 'desc' as const }, - { 'failures.doc_count': 'desc' as const }, - ] as estypes.AggregationsAggregateOrder, - }, - aggs: { - failures: { - filter: { - term: { - 'event.outcome': 'failure', - }, + }, + stack_by: { + terms: { + size: querySize, + field: stackByField, + order: [ + { 'successes.doc_count': 'desc' as const }, + { 'failures.doc_count': 'desc' as const }, + ] as estypes.AggregationsAggregateOrder, + }, + aggs: { + failures: { + filter: { + term: { + 'event.outcome': 'failure', }, - aggs: { - lastFailure: { - top_hits: { - size: 1, - _source: false, - sort: [{ '@timestamp': { order: 'desc' as const } }], - }, + }, + aggs: { + lastFailure: { + top_hits: { + size: 1, + _source: false, + sort: [{ '@timestamp': { order: 'desc' as const } }], }, }, }, - successes: { - filter: { - term: { - 'event.outcome': 'success', - }, + }, + successes: { + filter: { + term: { + 'event.outcome': 'success', }, - aggs: { - lastSuccess: { - top_hits: { - size: 1, - _source: false, - sort: [{ '@timestamp': { order: 'desc' as const } }], - }, + }, + aggs: { + lastSuccess: { + top_hits: { + size: 1, + _source: false, + sort: [{ '@timestamp': { order: 'desc' as const } }], }, }, }, }, }, }, - query: { - bool: { - filter, - }, + }, + query: { + bool: { + filter, }, - size: 0, - _source: false, - fields: [ - ...queryFields, - { - field: '@timestamp', - format: 'strict_date_optional_time', - }, - ], }, + size: 0, + _source: false, + fields: [ + ...queryFields, + { + field: '@timestamp', + format: 'strict_date_optional_time', + }, + ], track_total_hits: false, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/index.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/index.test.ts.snap index de0b3bc8d1a4d..9d134eee265c7 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/index.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/index.test.ts.snap @@ -11,65 +11,63 @@ Object { ], \\"ignore_unavailable\\": true, \\"track_total_hits\\": false, - \\"body\\": { - \\"query\\": { - \\"bool\\": { - \\"filter\\": [ - { - \\"terms\\": { - \\"event.dataset\\": [ - \\"entityanalytics_okta.user\\", - \\"entityanalytics_entra_id.user\\" - ] - } - }, - { - \\"term\\": { - \\"event.kind\\": \\"asset\\" - } + \\"query\\": { + \\"bool\\": { + \\"filter\\": [ + { + \\"terms\\": { + \\"event.dataset\\": [ + \\"entityanalytics_okta.user\\", + \\"entityanalytics_entra_id.user\\" + ] } - ], - \\"should\\": [ - { - \\"term\\": { - \\"user.name\\": \\"test-user-name\\" - } - }, - { - \\"terms\\": { - \\"user.email\\": [ - \\"test-user-name@mail.com\\" - ] - } + }, + { + \\"term\\": { + \\"event.kind\\": \\"asset\\" + } + } + ], + \\"should\\": [ + { + \\"term\\": { + \\"user.name\\": \\"test-user-name\\" } - ], - \\"minimum_should_match\\": 1 - } - }, - \\"size\\": 0, - \\"aggs\\": { - \\"datasets\\": { - \\"terms\\": { - \\"field\\": \\"event.dataset\\" }, - \\"aggs\\": { - \\"latest_hit\\": { - \\"top_hits\\": { - \\"fields\\": [ - \\"*\\", - \\"_index\\", - \\"_id\\" - ], - \\"_source\\": false, - \\"size\\": 1, - \\"sort\\": [ - { - \\"@timestamp\\": { - \\"order\\": \\"desc\\" - } + { + \\"terms\\": { + \\"user.email\\": [ + \\"test-user-name@mail.com\\" + ] + } + } + ], + \\"minimum_should_match\\": 1 + } + }, + \\"size\\": 0, + \\"aggs\\": { + \\"datasets\\": { + \\"terms\\": { + \\"field\\": \\"event.dataset\\" + }, + \\"aggs\\": { + \\"latest_hit\\": { + \\"top_hits\\": { + \\"fields\\": [ + \\"*\\", + \\"_index\\", + \\"_id\\" + ], + \\"_source\\": false, + \\"size\\": 1, + \\"sort\\": [ + { + \\"@timestamp\\": { + \\"order\\": \\"desc\\" } - ] - } + } + ] } } } diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/query.managed_user_details.dsl.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/query.managed_user_details.dsl.test.ts.snap index 081e61f95c24f..24d44df42861e 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/query.managed_user_details.dsl.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/__snapshots__/query.managed_user_details.dsl.test.ts.snap @@ -2,75 +2,73 @@ exports[`buildManagedUserDetailsQuery build query from options correctly 1`] = ` Object { - "allow_no_indices": true, - "body": Object { - "aggs": Object { - "datasets": Object { - "aggs": Object { - "latest_hit": Object { - "top_hits": Object { - "_source": false, - "fields": Array [ - "*", - "_index", - "_id", - ], - "size": 1, - "sort": Array [ - Object { - "@timestamp": Object { - "order": "desc", - }, + "aggs": Object { + "datasets": Object { + "aggs": Object { + "latest_hit": Object { + "top_hits": Object { + "_source": false, + "fields": Array [ + "*", + "_index", + "_id", + ], + "size": 1, + "sort": Array [ + Object { + "@timestamp": Object { + "order": "desc", }, - ], - }, + }, + ], }, }, - "terms": Object { - "field": "event.dataset", - }, }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "terms": Object { - "event.dataset": Array [ - "entityanalytics_okta.user", - "entityanalytics_entra_id.user", - ], - }, - }, - Object { - "term": Object { - "event.kind": "asset", - }, - }, - ], - "minimum_should_match": 1, - "should": Array [ - Object { - "term": Object { - "user.name": "test-user-name", - }, - }, - Object { - "terms": Object { - "user.email": Array [ - "test-user-name@mail.com", - ], - }, - }, - ], + "terms": Object { + "field": "event.dataset", }, }, - "size": 0, }, + "allow_no_indices": true, "ignore_unavailable": true, "index": Array [ "logs-*", ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "terms": Object { + "event.dataset": Array [ + "entityanalytics_okta.user", + "entityanalytics_entra_id.user", + ], + }, + }, + Object { + "term": Object { + "event.kind": "asset", + }, + }, + ], + "minimum_should_match": 1, + "should": Array [ + Object { + "term": Object { + "user.name": "test-user-name", + }, + }, + Object { + "terms": Object { + "user.email": Array [ + "test-user-name@mail.com", + ], + }, + }, + ], + }, + }, + "size": 0, "sort": Array [ Object { "@timestamp": "desc", diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/query.managed_user_details.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/query.managed_user_details.dsl.ts index 7fcd48d464e34..62bacd272f499 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/query.managed_user_details.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/managed_details/query.managed_user_details.dsl.ts @@ -35,34 +35,32 @@ export const buildManagedUserDetailsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - query: { bool: { filter, should, minimum_should_match: 1 } }, - size: 0, - aggs: { - datasets: { - terms: { - field: 'event.dataset', - }, - aggs: { - latest_hit: { - top_hits: { - fields: ['*', '_index', '_id'], // '_index' and '_id' are not returned by default - _source: false, - size: 1, - sort: [ - { - '@timestamp': { - order: 'desc' as const, - }, + query: { bool: { filter, should, minimum_should_match: 1 } }, + size: 0, + aggs: { + datasets: { + terms: { + field: 'event.dataset', + }, + aggs: { + latest_hit: { + top_hits: { + fields: ['*', '_index', '_id'], // '_index' and '_id' are not returned by default + _source: false, + size: 1, + sort: [ + { + '@timestamp': { + order: 'desc' as const, }, - ], - }, + }, + ], }, }, }, }, }, - sort: [{ '@timestamp': 'desc' }], + sort: [{ '@timestamp': 'desc' as const }], }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/index.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/index.test.ts.snap index 915b71e05cc3e..301688ce91b7e 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/index.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/index.test.ts.snap @@ -11,149 +11,147 @@ Object { ], \\"ignore_unavailable\\": true, \\"track_total_hits\\": false, - \\"body\\": { - \\"aggregations\\": { - \\"user_id\\": { - \\"terms\\": { - \\"field\\": \\"user.id\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } - } + \\"aggregations\\": { + \\"user_id\\": { + \\"terms\\": { + \\"field\\": \\"user.id\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" } }, - \\"user_domain\\": { - \\"terms\\": { - \\"field\\": \\"user.domain\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"user_domain\\": { + \\"terms\\": { + \\"field\\": \\"user.domain\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"user_name\\": { - \\"terms\\": { - \\"field\\": \\"user.name\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"user_name\\": { + \\"terms\\": { + \\"field\\": \\"user.name\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"host_os_name\\": { - \\"terms\\": { - \\"field\\": \\"host.os.name\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } + } + }, + \\"host_os_name\\": { + \\"terms\\": { + \\"field\\": \\"host.os.name\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } }, - \\"host_ip\\": { - \\"terms\\": { - \\"script\\": { - \\"source\\": \\"doc['host.ip']\\", - \\"lang\\": \\"painless\\" - }, - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } + } + } + }, + \\"host_ip\\": { + \\"terms\\": { + \\"script\\": { + \\"source\\": \\"doc['host.ip']\\", + \\"lang\\": \\"painless\\" }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } - } + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" } }, - \\"host_os_family\\": { - \\"terms\\": { - \\"field\\": \\"host.os.family\\", - \\"size\\": 10, - \\"order\\": { - \\"timestamp\\": \\"desc\\" - } - }, - \\"aggs\\": { - \\"timestamp\\": { - \\"max\\": { - \\"field\\": \\"@timestamp\\" - } + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" } } } }, - \\"query\\": { - \\"bool\\": { - \\"filter\\": [ - { - \\"bool\\": { - \\"must\\": [], - \\"filter\\": [ - { - \\"match_all\\": {} - }, - { - \\"match_phrase\\": { - \\"user.name\\": { - \\"query\\": \\"test_user\\" - } + \\"host_os_family\\": { + \\"terms\\": { + \\"field\\": \\"host.os.family\\", + \\"size\\": 10, + \\"order\\": { + \\"timestamp\\": \\"desc\\" + } + }, + \\"aggs\\": { + \\"timestamp\\": { + \\"max\\": { + \\"field\\": \\"@timestamp\\" + } + } + } + } + }, + \\"query\\": { + \\"bool\\": { + \\"filter\\": [ + { + \\"bool\\": { + \\"must\\": [], + \\"filter\\": [ + { + \\"match_all\\": {} + }, + { + \\"match_phrase\\": { + \\"user.name\\": { + \\"query\\": \\"test_user\\" } } - ], - \\"should\\": [], - \\"must_not\\": [] - } - }, - { - \\"term\\": { - \\"user.name\\": \\"bastion00.siem.estc.dev\\" - } - }, - { - \\"range\\": { - \\"@timestamp\\": { - \\"format\\": \\"strict_date_optional_time\\", - \\"gte\\": \\"2020-09-02T15:17:13.678Z\\", - \\"lte\\": \\"2020-09-03T15:17:13.678Z\\" } + ], + \\"should\\": [], + \\"must_not\\": [] + } + }, + { + \\"term\\": { + \\"user.name\\": \\"bastion00.siem.estc.dev\\" + } + }, + { + \\"range\\": { + \\"@timestamp\\": { + \\"format\\": \\"strict_date_optional_time\\", + \\"gte\\": \\"2020-09-02T15:17:13.678Z\\", + \\"lte\\": \\"2020-09-03T15:17:13.678Z\\" } } - ] - } - }, - \\"size\\": 0 - } + } + ] + } + }, + \\"size\\": 0 }", ], }, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/query.observed_user_details.dsl.test.ts.snap b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/query.observed_user_details.dsl.test.ts.snap index 0815b6851c936..cbc5fe7913989 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/query.observed_user_details.dsl.test.ts.snap +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/__snapshots__/query.observed_user_details.dsl.test.ts.snap @@ -2,154 +2,152 @@ exports[`buildUserDetailsQuery build query from options correctly 1`] = ` Object { - "allow_no_indices": true, - "body": Object { - "aggregations": Object { - "host_ip": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + "aggregations": Object { + "host_ip": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "order": Object { - "timestamp": "desc", - }, - "script": Object { - "lang": "painless", - "source": "doc['host.ip']", - }, - "size": 10, + }, + "terms": Object { + "order": Object { + "timestamp": "desc", + }, + "script": Object { + "lang": "painless", + "source": "doc['host.ip']", }, + "size": 10, }, - "host_os_family": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "host_os_family": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "host.os.family", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "host.os.family", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "host_os_name": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "host_os_name": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "host.os.name", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "host.os.name", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "user_domain": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "user_domain": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "user.domain", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "user.domain", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "user_id": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "user_id": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "user.id", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "user.id", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, - "user_name": Object { - "aggs": Object { - "timestamp": Object { - "max": Object { - "field": "@timestamp", - }, + }, + "user_name": Object { + "aggs": Object { + "timestamp": Object { + "max": Object { + "field": "@timestamp", }, }, - "terms": Object { - "field": "user.name", - "order": Object { - "timestamp": "desc", - }, - "size": 10, + }, + "terms": Object { + "field": "user.name", + "order": Object { + "timestamp": "desc", }, + "size": 10, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "bool": Object { - "filter": Array [ - Object { - "match_all": Object {}, - }, - Object { - "match_phrase": Object { - "user.name": Object { - "query": "test_user", - }, + }, + "allow_no_indices": true, + "ignore_unavailable": true, + "index": Array [ + "test_indices*", + ], + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "bool": Object { + "filter": Array [ + Object { + "match_all": Object {}, + }, + Object { + "match_phrase": Object { + "user.name": Object { + "query": "test_user", }, }, - ], - "must": Array [], - "must_not": Array [], - "should": Array [], - }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], }, - Object { - "term": Object { - "user.name": "bastion00.siem.estc.dev", - }, + }, + Object { + "term": Object { + "user.name": "bastion00.siem.estc.dev", }, - Object { - "range": Object { - "@timestamp": Object { - "format": "strict_date_optional_time", - "gte": "2020-09-02T15:17:13.678Z", - "lte": "2020-09-03T15:17:13.678Z", - }, + }, + Object { + "range": Object { + "@timestamp": Object { + "format": "strict_date_optional_time", + "gte": "2020-09-02T15:17:13.678Z", + "lte": "2020-09-03T15:17:13.678Z", }, }, - ], - }, + }, + ], }, - "size": 0, }, - "ignore_unavailable": true, - "index": Array [ - "test_indices*", - ], + "size": 0, "track_total_hits": false, } `; diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/query.observed_user_details.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/query.observed_user_details.dsl.ts index 081b415f4bd75..36cb38f275414 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/query.observed_user_details.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/users/observed_details/query.observed_user_details.dsl.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ISearchRequestParams } from '@kbn/search-types'; import type { ObservedUserDetailsRequestOptions } from '../../../../../../common/api/search_strategy'; import { createQueryFilterClauses } from '../../../../../utils/build_query'; @@ -37,13 +37,11 @@ export const buildObservedUserDetailsQuery = ({ index: defaultIndex, ignore_unavailable: true, track_total_hits: false, - body: { - aggregations: { - ...buildFieldsTermAggregation(USER_FIELDS), - }, - query: { bool: { filter } }, - size: 0, + aggregations: { + ...buildFieldsTermAggregation(USER_FIELDS), }, + query: { bool: { filter } }, + size: 0, }; return dslQuery; diff --git a/x-pack/solutions/security/plugins/security_solution/server/usage/detections/ml_jobs/transform_utils/get_job_correlations.ts b/x-pack/solutions/security/plugins/security_solution/server/usage/detections/ml_jobs/transform_utils/get_job_correlations.ts index 76d815d437861..579a0b4c488d3 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/usage/detections/ml_jobs/transform_utils/get_job_correlations.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/usage/detections/ml_jobs/transform_utils/get_job_correlations.ts @@ -56,11 +56,11 @@ export const getJobCorrelations = ({ datafeed_id: datafeed?.datafeed_id, state: datafeed?.state, timing_stats: { - bucket_count: datafeed?.timing_stats.bucket_count, + bucket_count: datafeed?.timing_stats?.bucket_count, exponential_average_search_time_per_hour_ms: - datafeed?.timing_stats.exponential_average_search_time_per_hour_ms, - search_count: datafeed?.timing_stats.search_count, - total_search_time_ms: datafeed?.timing_stats.total_search_time_ms, + datafeed?.timing_stats?.exponential_average_search_time_per_hour_ms, + search_count: datafeed?.timing_stats?.search_count, + total_search_time_ms: datafeed?.timing_stats?.total_search_time_ms, }, }, }; diff --git a/x-pack/solutions/security/plugins/security_solution/server/usage/risk_engine/get_risk_engine_metrics.ts b/x-pack/solutions/security/plugins/security_solution/server/usage/risk_engine/get_risk_engine_metrics.ts index 481696360afaf..3f6c4e75841a6 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/usage/risk_engine/get_risk_engine_metrics.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/usage/risk_engine/get_risk_engine_metrics.ts @@ -80,7 +80,7 @@ const getEntitiesAggregationData = async ({ } >({ index, - body: bodyRequest, + ...bodyRequest, }); return { diff --git a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.ts b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.ts index 6687c3dfed48c..3b0d98eba9012 100644 --- a/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.ts +++ b/x-pack/solutions/security/plugins/security_solution_serverless/server/cloud_security/cloud_security_metering_task.ts @@ -190,11 +190,12 @@ export const getAssetAggByCloudSecuritySolution = async ( ): Promise => { const assetsAggQuery = getAssetAggQueryByCloudSecuritySolution(cloudSecuritySolution); + // @ts-expect-error elasticsearch@9.0.0 The types are tripping because of the dynamic aggs const response = await esClient.search(assetsAggQuery); if (!response.aggregations) return; - return response.aggregations; + return response.aggregations as AssetCountAggregation; }; const indexHasDataInDateRange = async ( diff --git a/x-pack/solutions/security/plugins/session_view/server/routes/get_total_io_bytes_route.ts b/x-pack/solutions/security/plugins/session_view/server/routes/get_total_io_bytes_route.ts index 7d54654c89cdc..f03466b346295 100644 --- a/x-pack/solutions/security/plugins/session_view/server/routes/get_total_io_bytes_route.ts +++ b/x-pack/solutions/security/plugins/session_view/server/routes/get_total_io_bytes_route.ts @@ -45,29 +45,27 @@ export const registerGetTotalIOBytesRoute = (router: IRouter, logger: Logger) => try { const search = await client.search({ index: [index], - body: { - query: { - bool: { - must: [ - { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, - { term: { [EVENT_ACTION]: 'text_output' } }, - { - range: { - // optimization to prevent data before this session from being hit. - [TIMESTAMP_PROPERTY]: { - gte: sessionStartTime, - }, + query: { + bool: { + must: [ + { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, + { term: { [EVENT_ACTION]: 'text_output' } }, + { + range: { + // optimization to prevent data before this session from being hit. + [TIMESTAMP_PROPERTY]: { + gte: sessionStartTime, }, }, - ], - }, - }, - size: 0, - aggs: { - total_bytes_captured: { - sum: { - field: TOTAL_BYTES_CAPTURED_PROPERTY, }, + ], + }, + }, + size: 0, + aggs: { + total_bytes_captured: { + sum: { + field: TOTAL_BYTES_CAPTURED_PROPERTY, }, }, }, diff --git a/x-pack/solutions/security/plugins/session_view/server/routes/io_events_route.ts b/x-pack/solutions/security/plugins/session_view/server/routes/io_events_route.ts index 3e73517a978c3..b257a6437b137 100644 --- a/x-pack/solutions/security/plugins/session_view/server/routes/io_events_route.ts +++ b/x-pack/solutions/security/plugins/session_view/server/routes/io_events_route.ts @@ -60,28 +60,26 @@ export const registerIOEventsRoute = (router: IRouter, logger: Logger) => { try { const search = await client.search({ index: [index], - body: { - query: { - bool: { - must: [ - { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, - { term: { [EVENT_ACTION]: 'text_output' } }, - { - range: { - // optimization to prevent data before this session from being hit. - [TIMESTAMP_PROPERTY]: { - gte: sessionStartTime, - }, + query: { + bool: { + must: [ + { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, + { term: { [EVENT_ACTION]: 'text_output' } }, + { + range: { + // optimization to prevent data before this session from being hit. + [TIMESTAMP_PROPERTY]: { + gte: sessionStartTime, }, }, - ], - }, + }, + ], }, - size: Math.min(pageSize, IO_EVENTS_PER_PAGE), - sort: [{ [TIMESTAMP]: 'asc' }], - search_after: cursor ? [cursor] : undefined, - fields: IO_EVENT_FIELDS, }, + size: Math.min(pageSize, IO_EVENTS_PER_PAGE), + sort: [{ [TIMESTAMP]: 'asc' }], + search_after: cursor ? [cursor] : undefined, + fields: IO_EVENT_FIELDS, }); const events = search.hits.hits; @@ -129,23 +127,21 @@ export const searchProcessWithIOEvents = async ( try { const search = await client.search({ index: [index], - body: { - query: { - bool: { - must: [ - { term: { [EVENT_ACTION]: 'text_output' } }, - { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, - ...rangeFilter, - ], - }, + query: { + bool: { + must: [ + { term: { [EVENT_ACTION]: 'text_output' } }, + { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, + ...rangeFilter, + ], }, - size: 0, - aggs: { - custom_agg: { - terms: { - field: PROCESS_ENTITY_ID_PROPERTY, - size: PROCESS_EVENTS_PER_PAGE, - }, + }, + size: 0, + aggs: { + custom_agg: { + terms: { + field: PROCESS_ENTITY_ID_PROPERTY, + size: PROCESS_EVENTS_PER_PAGE, }, }, }, diff --git a/x-pack/solutions/security/plugins/session_view/server/routes/process_events_route.ts b/x-pack/solutions/security/plugins/session_view/server/routes/process_events_route.ts index b30b3b6ddcc51..bbb4fecdbfa71 100644 --- a/x-pack/solutions/security/plugins/session_view/server/routes/process_events_route.ts +++ b/x-pack/solutions/security/plugins/session_view/server/routes/process_events_route.ts @@ -113,37 +113,35 @@ export const fetchEventsAndScopedAlerts = async ( const search = await client.search({ index: [index], - body: { - query: { - bool: { - must: [ - { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, - { - bool: { - should: [ - { term: { [EVENT_ACTION]: EVENT_ACTION_FORK } }, - { term: { [EVENT_ACTION]: EVENT_ACTION_EXEC } }, - { term: { [EVENT_ACTION]: EVENT_ACTION_EXECUTED } }, - { term: { [EVENT_ACTION]: EVENT_ACTION_END } }, - ], - }, + query: { + bool: { + must: [ + { term: { [ENTRY_SESSION_ENTITY_ID_PROPERTY]: sessionEntityId } }, + { + bool: { + should: [ + { term: { [EVENT_ACTION]: EVENT_ACTION_FORK } }, + { term: { [EVENT_ACTION]: EVENT_ACTION_EXEC } }, + { term: { [EVENT_ACTION]: EVENT_ACTION_EXECUTED } }, + { term: { [EVENT_ACTION]: EVENT_ACTION_END } }, + ], }, - { - range: { - // optimization to prevent data before this session from being hit. - [TIMESTAMP_PROPERTY]: { - gte: sessionStartTime, - }, + }, + { + range: { + // optimization to prevent data before this session from being hit. + [TIMESTAMP_PROPERTY]: { + gte: sessionStartTime, }, }, - ], - }, + }, + ], }, - size: Math.min(pageSize, PROCESS_EVENTS_PER_PAGE), - sort: [{ '@timestamp': forward ? 'asc' : 'desc' }], - search_after: cursorMillis ? [cursorMillis] : undefined, - fields: PROCESS_EVENT_FIELDS, }, + size: Math.min(pageSize, PROCESS_EVENTS_PER_PAGE), + sort: [{ '@timestamp': forward ? 'asc' : 'desc' }], + search_after: cursorMillis ? [cursorMillis] : undefined, + fields: PROCESS_EVENT_FIELDS, }); let events = search.hits.hits; diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.test.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.test.ts index d0e8e7d29d660..495021791cb2f 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.test.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.test.ts @@ -37,11 +37,9 @@ describe('FetchIndicatorByIdService', () => { expect(mockedSearchService.search).toHaveBeenCalledWith( expect.objectContaining({ params: { - body: { - fields: [{ field: '*', include_unmapped: true }], - query: expect.objectContaining({ bool: expect.anything() }), - size: 1, - }, + fields: [{ field: '*', include_unmapped: true }], + query: expect.objectContaining({ bool: expect.anything() }), + size: 1, }, }), expect.anything() diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.ts index 7e26c41f0ad58..fb54a9d84b19d 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/cases/services/fetch_indicator_by_id.ts @@ -66,11 +66,9 @@ export const createFetchIndicatorById = searchService, { params: { - body: { - query, - fields, - size: 1, - }, + query, + fields, + size: 1, }, }, { diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/hooks/use_total_count.tsx b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/hooks/use_total_count.tsx index f2b9fcefe11f7..90cd05dcf421a 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/hooks/use_total_count.tsx +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/hooks/use_total_count.tsx @@ -47,10 +47,8 @@ export const useIndicatorsTotalCount = () => { const req = { params: { index: selectedPatterns, - body: { - size: 0, - query, - }, + size: 0, + query, }, }; diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts index b6ec332970120..9f78625e7f4f5 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.test.ts @@ -94,9 +94,7 @@ describe('FetchAggregatedIndicatorsService', () => { expect(mockedSearchService.search).toHaveBeenCalledWith( expect.objectContaining({ params: expect.objectContaining({ - body: expect.objectContaining({ - query: expect.objectContaining({ bool: expect.anything() }), - }), + query: expect.objectContaining({ bool: expect.anything() }), index: [], }), factoryQueryType: FactoryQueryType.Barchart, diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts index 13cb5824b599a..94fbe99736e65 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_aggregated_indicators.ts @@ -126,7 +126,7 @@ export const createFetchAggregatedIndicators = { params: { index: selectedPatterns, - body: searchRequestBody, + ...searchRequestBody, }, factoryQueryType: FactoryQueryType.Barchart, dateRange: { diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.test.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.test.ts index 3536fc4903ba7..9ec4ebb84117c 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.test.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.test.ts @@ -44,13 +44,11 @@ describe('FetchIndicatorsService', () => { expect(mockedSearchService.search).toHaveBeenCalledWith( expect.objectContaining({ params: { - body: { - fields: [{ field: '*', include_unmapped: true }], - from: 0, - query: expect.objectContaining({ bool: expect.anything() }), - size: 25, - sort: [], - }, + fields: [{ field: '*', include_unmapped: true }], + from: 0, + query: expect.objectContaining({ bool: expect.anything() }), + size: 25, + sort: [], index: [], }, factoryQueryType: FactoryQueryType.IndicatorGrid, diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.ts index d92e2788abdc2..e5babd473b94c 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/modules/indicators/services/fetch_indicators.ts @@ -75,7 +75,7 @@ export const createFetchIndicators = { params: { index: selectedPatterns, - body: searchRequestBody, + ...searchRequestBody, }, factoryQueryType: FactoryQueryType.IndicatorGrid, }, diff --git a/x-pack/solutions/security/plugins/threat_intelligence/public/utils/search.ts b/x-pack/solutions/security/plugins/threat_intelligence/public/utils/search.ts index e183ba7e272b2..34694c69881a6 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/public/utils/search.ts +++ b/x-pack/solutions/security/plugins/threat_intelligence/public/utils/search.ts @@ -57,7 +57,7 @@ const requestInspector = ( } inspectorRequest.stats({}).ok({ json: response }); - inspectorRequest.json(searchRequest.params?.body || {}); + inspectorRequest.json(searchRequest.params || {}); }, resetRequest() { diff --git a/x-pack/solutions/security/plugins/threat_intelligence/scripts/generate_indicators.js b/x-pack/solutions/security/plugins/threat_intelligence/scripts/generate_indicators.js index daa869c76cf70..82c625c1923b7 100644 --- a/x-pack/solutions/security/plugins/threat_intelligence/scripts/generate_indicators.js +++ b/x-pack/solutions/security/plugins/threat_intelligence/scripts/generate_indicators.js @@ -5,7 +5,7 @@ * 2.0. */ -const { Client } = require('@elastic/elasticsearch'); +const { Client, HttpConnection } = require('@elastic/elasticsearch'); const { faker } = require('@faker-js/faker'); const THREAT_INDEX = 'logs-ti'; @@ -31,6 +31,8 @@ const client = new Client({ username: 'elastic', password: 'changeme', }, + Connection: HttpConnection, + requestTimeout: 30_000, }); const main = async () => { diff --git a/x-pack/test/accessibility/apps/group1/helpers.ts b/x-pack/test/accessibility/apps/group1/helpers.ts index 3b46eb7872af1..19a985907a104 100644 --- a/x-pack/test/accessibility/apps/group1/helpers.ts +++ b/x-pack/test/accessibility/apps/group1/helpers.ts @@ -28,18 +28,16 @@ export async function putSamplePipeline(client: Client) { return await client.ingest.putPipeline( { id: 'testPipeline', - body: { - description: 'describe pipeline', - version: 123, - processors: [ - { - set: { - field: 'foo', - value: 'bar', - }, + description: 'describe pipeline', + version: 123, + processors: [ + { + set: { + field: 'foo', + value: 'bar', }, - ], - }, + }, + ], }, { meta: true } ); diff --git a/x-pack/test/accessibility/apps/group1/index_lifecycle_management.ts b/x-pack/test/accessibility/apps/group1/index_lifecycle_management.ts index c89f715afe1f3..98d805ba06ac9 100644 --- a/x-pack/test/accessibility/apps/group1/index_lifecycle_management.ts +++ b/x-pack/test/accessibility/apps/group1/index_lifecycle_management.ts @@ -67,7 +67,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { before(async () => { await esClient.snapshot.createRepository({ name: REPO_NAME, - body: { + repository: { type: 'fs', settings: { // use one of the values defined in path.repo in test/functional/config.base.js @@ -76,19 +76,17 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { }, verify: false, }); - await esClient.ilm.putLifecycle({ name: POLICY_NAME, body: POLICY_ALL_PHASES }); + await esClient.ilm.putLifecycle({ name: POLICY_NAME, ...POLICY_ALL_PHASES }); await esClient.indices.putIndexTemplate({ name: indexTemplateName, - body: { - template: { - settings: { - lifecycle: { - name: POLICY_NAME, - }, + template: { + settings: { + lifecycle: { + name: POLICY_NAME, }, }, - index_patterns: ['test*'], }, + index_patterns: ['test*'], }); }); diff --git a/x-pack/test/accessibility/apps/group3/remote_clusters.ts b/x-pack/test/accessibility/apps/group3/remote_clusters.ts index 7f7438e44d4e2..071cc02e227af 100644 --- a/x-pack/test/accessibility/apps/group3/remote_clusters.ts +++ b/x-pack/test/accessibility/apps/group3/remote_clusters.ts @@ -152,7 +152,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { modes.forEach((mode: string) => { describe(`Edit remote cluster (${mode} mode)`, () => { const clusterName = mode === 'sniff' ? 'clusterSniffMode' : 'clusterProxyMode'; - const body = + const settings = mode === 'sniff' ? getPayloadClusterSniffMode(clusterName) : getPayloadClusterProxyMode(clusterName); @@ -162,11 +162,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { }); before(async () => { - await esClient.cluster.putSettings({ body }); + await esClient.cluster.putSettings(settings); }); after(async () => { - await esClient.cluster.putSettings({ body: getDeleteClusterPayload(clusterName) }); + await esClient.cluster.putSettings(getDeleteClusterPayload(clusterName)); }); it('renders the list view with remote clusters', async () => { diff --git a/x-pack/test/alerting_api_integration/common/lib/task_manager_utils.ts b/x-pack/test/alerting_api_integration/common/lib/task_manager_utils.ts index a4ab6442df1fd..82655d080b906 100644 --- a/x-pack/test/alerting_api_integration/common/lib/task_manager_utils.ts +++ b/x-pack/test/alerting_api_integration/common/lib/task_manager_utils.ts @@ -25,34 +25,32 @@ export class TaskManagerUtils { return await this.retry.try(async () => { const searchResult = await this.es.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.id': `task:${id}`, - }, + query: { + bool: { + must: [ + { + term: { + 'task.id': `task:${id}`, }, - { - terms: { - 'task.scope': ['actions', 'alerting'], - }, + }, + { + terms: { + 'task.scope': ['actions', 'alerting'], }, - { - range: { - 'task.scheduledAt': { - gte: taskRunAtFilter.getTime().toString(), - }, + }, + { + range: { + 'task.scheduledAt': { + gte: taskRunAtFilter.getTime().toString(), }, }, - { - term: { - 'task.enabled': true, - }, + }, + { + term: { + 'task.enabled': true, }, - ], - }, + }, + ], }, }, }); @@ -67,24 +65,22 @@ export class TaskManagerUtils { return await this.retry.try(async () => { const searchResult = await this.es.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - terms: { - 'task.scope': ['actions', 'alerting'], - }, + query: { + bool: { + must: [ + { + terms: { + 'task.scope': ['actions', 'alerting'], }, - { - range: { - 'task.scheduledAt': { - gte: taskRunAtFilter.getTime().toString(), - }, + }, + { + range: { + 'task.scheduledAt': { + gte: taskRunAtFilter.getTime().toString(), }, }, - ], - }, + }, + ], }, }, }); @@ -100,31 +96,29 @@ export class TaskManagerUtils { return await this.retry.try(async () => { const searchResult = await this.es.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - terms: { - 'task.scope': ['actions', 'alerting'], - }, + query: { + bool: { + must: [ + { + terms: { + 'task.scope': ['actions', 'alerting'], }, - { - range: { - 'task.scheduledAt': { - gte: taskRunAtFilter.getTime().toString(), - }, + }, + { + range: { + 'task.scheduledAt': { + gte: taskRunAtFilter.getTime().toString(), }, }, - ], - must_not: [ - { - term: { - 'task.status': 'idle', - }, + }, + ], + must_not: [ + { + term: { + 'task.status': 'idle', }, - ], - }, + }, + ], }, }, }); @@ -140,24 +134,22 @@ export class TaskManagerUtils { return await this.retry.try(async () => { const searchResult = await this.es.search({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - bool: { - must: [ - { - term: { - type: 'action_task_params', - }, + query: { + bool: { + must: [ + { + term: { + type: 'action_task_params', }, - { - range: { - updated_at: { - gte: createdAtFilter.getTime().toString(), - }, + }, + { + range: { + updated_at: { + gte: createdAtFilter.getTime().toString(), }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/common/plugins/alerts/server/action_types.ts b/x-pack/test/alerting_api_integration/common/plugins/alerts/server/action_types.ts index bf69461b0382a..88098a38992f4 100644 --- a/x-pack/test/alerting_api_integration/common/plugins/alerts/server/action_types.ts +++ b/x-pack/test/alerting_api_integration/common/plugins/alerts/server/action_types.ts @@ -126,7 +126,7 @@ function getIndexRecordActionType() { await services.scopedClusterClient.index({ index: params.index, refresh: 'wait_for', - body: { + document: { params, config, secrets, diff --git a/x-pack/test/alerting_api_integration/common/plugins/alerts/server/rule_types.ts b/x-pack/test/alerting_api_integration/common/plugins/alerts/server/rule_types.ts index a3f0f39e908ed..52c847b6c7ab1 100644 --- a/x-pack/test/alerting_api_integration/common/plugins/alerts/server/rule_types.ts +++ b/x-pack/test/alerting_api_integration/common/plugins/alerts/server/rule_types.ts @@ -121,7 +121,7 @@ async function alwaysFiringExecutor(alertExecutorOptions: any) { await services.scopedClusterClient.asCurrentUser.index({ index: params.index, refresh: 'wait_for', - body: { + document: { state, params, reference: params.reference, @@ -1135,7 +1135,7 @@ async function getSignalDocs(es: ElasticsearchClient, source: string, reference: index: ES_TEST_INDEX_NAME, size: 1000, _source: false, - body, + ...body, }; const result = await es.search(params, { meta: true }); return result?.body?.hits?.hits || []; diff --git a/x-pack/test/alerting_api_integration/observability/helpers/alerting_wait_for_helpers.ts b/x-pack/test/alerting_api_integration/observability/helpers/alerting_wait_for_helpers.ts index edc5ca8d35a60..19c187ffd1ec4 100644 --- a/x-pack/test/alerting_api_integration/observability/helpers/alerting_wait_for_helpers.ts +++ b/x-pack/test/alerting_api_integration/observability/helpers/alerting_wait_for_helpers.ts @@ -9,10 +9,7 @@ import { ToolingLog } from '@kbn/tooling-log'; import type SuperTest from 'supertest'; import type { Client } from '@elastic/elasticsearch'; -import type { - AggregationsAggregate, - SearchResponse, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsAggregate, SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import type { RetryService } from '@kbn/ftr-common-functional-services'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { retry } from '../../common/retry'; @@ -82,7 +79,7 @@ export async function waitForDocumentInIndex({ index: indexName, rest_total_hits_as_int: true, ignore_unavailable: true, - body: filters + ...(filters ? { query: { bool: { @@ -90,7 +87,7 @@ export async function waitForDocumentInIndex({ }, }, } - : undefined, + : undefined), }); if (!response.hits.total || (response.hits.total as number) < docCountTarget) { logger.debug(`Document count is ${response.hits.total}, should be ${docCountTarget}`); @@ -131,18 +128,16 @@ export async function waitForAlertInIndex({ testFn: async () => { const response = await esClient.search({ index: indexName, - body: { - query: { - bool: { - filter: [ - { - term: { - 'kibana.alert.rule.uuid': ruleId, - }, + query: { + bool: { + filter: [ + { + term: { + 'kibana.alert.rule.uuid': ruleId, }, - ...filters, - ], - }, + }, + ...filters, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/observability/synthetics/synthetics_rule_helper.ts b/x-pack/test/alerting_api_integration/observability/synthetics/synthetics_rule_helper.ts index 50d54fa834939..32d53e49b0fd7 100644 --- a/x-pack/test/alerting_api_integration/observability/synthetics/synthetics_rule_helper.ts +++ b/x-pack/test/alerting_api_integration/observability/synthetics/synthetics_rule_helper.ts @@ -43,12 +43,10 @@ export class SyntheticsRuleHelper { async createIndexAction() { await this.esClient.indices.create({ index: this.alertActionIndex, - body: { - mappings: { - properties: { - 'monitor.id': { - type: 'keyword', - }, + mappings: { + properties: { + 'monitor.id': { + type: 'keyword', }, }, }, diff --git a/x-pack/test/alerting_api_integration/packages/helpers/es_test_index_tool.ts b/x-pack/test/alerting_api_integration/packages/helpers/es_test_index_tool.ts index b0de8872e177d..5286cb21b150c 100644 --- a/x-pack/test/alerting_api_integration/packages/helpers/es_test_index_tool.ts +++ b/x-pack/test/alerting_api_integration/packages/helpers/es_test_index_tool.ts @@ -21,67 +21,65 @@ export class ESTestIndexTool { return await this.es.indices.create( { index: this.index, - body: { - mappings: { - properties: { - source: { - type: 'keyword', - }, - reference: { - type: 'keyword', - }, - params: { - enabled: false, - type: 'object', - }, - config: { - enabled: false, - type: 'object', - }, - state: { - enabled: false, - type: 'object', - }, - date: { - type: 'date', - format: 'strict_date_time', - }, - date_epoch_millis: { - type: 'date', - format: 'epoch_millis', - }, - testedValue: { - type: 'long', - }, - testedValueFloat: { - type: 'float', - }, - testedValueUnsigned: { - type: 'unsigned_long', - }, - group: { - type: 'keyword', - }, - '@timestamp': { - type: 'date', - }, - host: { - properties: { - hostname: { - type: 'text', - fields: { - keyword: { - type: 'keyword', - ignore_above: 256, - }, + mappings: { + properties: { + source: { + type: 'keyword', + }, + reference: { + type: 'keyword', + }, + params: { + enabled: false, + type: 'object', + }, + config: { + enabled: false, + type: 'object', + }, + state: { + enabled: false, + type: 'object', + }, + date: { + type: 'date', + format: 'strict_date_time', + }, + date_epoch_millis: { + type: 'date', + format: 'epoch_millis', + }, + testedValue: { + type: 'long', + }, + testedValueFloat: { + type: 'float', + }, + testedValueUnsigned: { + type: 'unsigned_long', + }, + group: { + type: 'keyword', + }, + '@timestamp': { + type: 'date', + }, + host: { + properties: { + hostname: { + type: 'text', + fields: { + keyword: { + type: 'keyword', + ignore_above: 256, }, }, - id: { - type: 'keyword', - }, - name: { - type: 'keyword', - }, + }, + id: { + type: 'keyword', + }, + name: { + type: 'keyword', }, }, }, @@ -113,7 +111,7 @@ export class ESTestIndexTool { async search(source: string, reference?: string) { const body = reference ? { - sort: [{ '@timestamp': 'asc' }], + sort: [{ '@timestamp': 'asc' as const }], query: { bool: { must: [ @@ -132,7 +130,7 @@ export class ESTestIndexTool { }, } : { - sort: [{ '@timestamp': 'asc' }], + sort: [{ '@timestamp': 'asc' as const }], query: { term: { source, @@ -142,7 +140,7 @@ export class ESTestIndexTool { const params = { index: this.index, size: 1000, - body, + ...body, }; const result = await this.es.search(params, { meta: true }); result.body.hits.hits = result.body.hits.hits.map((hit) => { @@ -160,10 +158,8 @@ export class ESTestIndexTool { const params = { index: this.index, size, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }; return await this.es.search(params, { meta: true }); @@ -183,11 +179,12 @@ export class ESTestIndexTool { async waitForDocs(source: string, reference: string, numDocs: number = 1) { return await this.retry.try(async () => { const searchResult = await this.search(source, reference); - // @ts-expect-error doesn't handle total: number - const value = searchResult.body.hits.total.value?.value || searchResult.body.hits.total.value; - if (value < numDocs) { - // @ts-expect-error doesn't handle total: number - throw new Error(`Expected ${numDocs} but received ${searchResult.body.hits.total.value}.`); + const value = + typeof searchResult.body.hits.total === 'number' + ? searchResult.body.hits.total + : searchResult.body.hits.total?.value; + if (value! < numDocs) { + throw new Error(`Expected ${numDocs} but received ${value}.`); } return searchResult.body.hits.hits; }); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/api_key.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/api_key.ts index a36d7708bb99c..b0648e0783a49 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/api_key.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/api_key.ts @@ -61,10 +61,8 @@ export default function apiKeyBackfillTests({ getService }: FtrProviderContext) async function getApiKeysPendingInvalidation() { const result = await es.search({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { type: 'api_key_pending_invalidation' }, - }, + query: { + term: { type: 'api_key_pending_invalidation' }, }, }); return result.hits.hits.map((hit) => hit._source); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/delete.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/delete.ts index 9a2f0777c6403..3d3f2329288a6 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/delete.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/delete.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import moment from 'moment'; import { asyncForEach } from '@kbn/std'; -import { GetResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { GetResponse } from '@elastic/elasticsearch/lib/api/types'; import { UserAtSpaceScenarios } from '../../../../scenarios'; import { getTestRuleData, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/task_runner_with_actions.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/task_runner_with_actions.ts index f155f40a61f05..152d9e6835894 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/task_runner_with_actions.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/task_runner_with_actions.ts @@ -129,7 +129,7 @@ export default function scheduleBackfillTests({ getService }: FtrProviderContext // verify that the correct number of actions were executed const actions = await es.search({ index: TEST_ACTIONS_INDEX, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); // 3 backfill executions resulted in alerts so 3 notifications should have @@ -191,7 +191,7 @@ export default function scheduleBackfillTests({ getService }: FtrProviderContext // verify that the correct number of actions were executed const actions = await es.search({ index: TEST_ACTIONS_INDEX, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); // 3 backfill executions resulted in 9 alerts so 9 notifications should have @@ -257,7 +257,7 @@ export default function scheduleBackfillTests({ getService }: FtrProviderContext // verify that the correct number of actions were executed const actions = await es.search({ index: TEST_ACTIONS_INDEX, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); // no actions should be generated diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/test_utils.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/test_utils.ts index ad4fde6b39ec6..975473f209e33 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/test_utils.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group1/tests/alerting/backfill/test_utils.ts @@ -12,7 +12,7 @@ import moment from 'moment'; import { FtrProviderContext, RetryService } from '@kbn/ftr-common-functional-services'; import { AD_HOC_RUN_SAVED_OBJECT_TYPE } from '@kbn/alerting-plugin/server/saved_objects'; import { ALERT_ORIGINAL_TIME } from '@kbn/security-solution-plugin/common/field_maps/field_names'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { TaskManagerDoc, getEventLog } from '../../../../../common/lib'; import { DOCUMENT_REFERENCE, @@ -89,10 +89,8 @@ export async function queryForAlertDocs( ): Promise>> { const searchResult = await es.search({ index, - body: { - sort: [{ [ALERT_ORIGINAL_TIME]: { order: 'asc' } }], - query: { match_all: {} }, - }, + sort: [{ [ALERT_ORIGINAL_TIME]: { order: 'asc' } }], + query: { match_all: {} }, }); return searchResult.hits.hits as Array>; } @@ -100,22 +98,20 @@ export async function queryForAlertDocs( export async function searchScheduledTask(es: Client, id: string) { const searchResult = await es.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.id': `task:${id}`, - }, + query: { + bool: { + must: [ + { + term: { + 'task.id': `task:${id}`, }, - { - terms: { - 'task.scope': ['alerting'], - }, + }, + { + terms: { + 'task.scope': ['alerting'], }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts index d9b0f387eb749..a9546231c9d9a 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group3/tests/alerting/user_managed_api_key.ts @@ -581,7 +581,8 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext expect(response.statusCode).to.eql(204); const invalidateResponse = await es.security.invalidateApiKey({ - body: { ids: ['abc'], owner: false }, + ids: ['abc'], + owner: false, }); expect(invalidateResponse.previously_invalidated_api_keys).to.eql([]); }); @@ -594,7 +595,8 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext expect(response.status).to.eql(204); const invalidateResponse = await es.security.invalidateApiKey({ - body: { ids: ['abc'], owner: false }, + ids: ['abc'], + owner: false, }); expect(invalidateResponse.previously_invalidated_api_keys).to.eql([]); }); @@ -609,7 +611,8 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext expect(response.statusCode).to.eql(200); const invalidateResponse = await es.security.invalidateApiKey({ - body: { ids: ['abc'], owner: false }, + ids: ['abc'], + owner: false, }); expect(invalidateResponse.previously_invalidated_api_keys).to.eql([]); }); @@ -623,7 +626,8 @@ export default function userManagedApiKeyTest({ getService }: FtrProviderContext expect(response.status).to.eql(200); const invalidateResponse = await es.security.invalidateApiKey({ - body: { ids: ['abc'], owner: false }, + ids: ['abc'], + owner: false, }); expect(invalidateResponse.previously_invalidated_api_keys).to.eql([]); }); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts index c3cc9f410b203..28fd1f9585b0c 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group4/tests/alerting/alerts.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { expect as expectExpect } from 'expect'; import { omit, padStart } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server'; import { TaskRunning, TaskRunningStage } from '@kbn/task-manager-plugin/server/task_running'; import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server'; @@ -537,34 +537,32 @@ instanceStateValue: true TaskRunning >({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.status': 'idle', - }, + query: { + bool: { + must: [ + { + term: { + 'task.status': 'idle', }, - { - term: { - 'task.attempts': 1, - }, + }, + { + term: { + 'task.attempts': 1, }, - { - term: { - 'task.taskType': 'actions:test.rate-limit', - }, + }, + { + term: { + 'task.taskType': 'actions:test.rate-limit', }, - { - range: { - 'task.scheduledAt': { - gte: testStart, - }, + }, + { + range: { + 'task.scheduledAt': { + gte: testStart, }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack.ts index 2fe1aceb60132..7e120becd11fb 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack.ts @@ -82,7 +82,7 @@ export default function bulkUntrackTests({ getService }: FtrProviderContext) { hits: { hits: activeAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); activeAlerts.forEach((activeAlert: any) => { @@ -94,7 +94,7 @@ export default function bulkUntrackTests({ getService }: FtrProviderContext) { hits: { hits: activeAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); const ids = activeAlerts.map((activeAlert: any) => activeAlert._source[ALERT_UUID]); @@ -124,7 +124,7 @@ export default function bulkUntrackTests({ getService }: FtrProviderContext) { hits: { hits: untrackedAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); untrackedAlerts.forEach((untrackedAlert: any) => { @@ -174,7 +174,7 @@ export default function bulkUntrackTests({ getService }: FtrProviderContext) { hits: { hits: activeAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); const ids = activeAlerts.map((activeAlert: any) => activeAlert._source[ALERT_UUID]); @@ -205,7 +205,7 @@ export default function bulkUntrackTests({ getService }: FtrProviderContext) { hits: { hits: alerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); const activeAlertsRemaining = []; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack_by_query.ts b/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack_by_query.ts index 66d04b723ca03..e8a0421620550 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack_by_query.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/group5/tests/alerting/bulk_untrack_by_query.ts @@ -104,7 +104,7 @@ export default function bulkUntrackByQueryTests({ getService }: FtrProviderConte hits: { hits: activeAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); activeAlerts.forEach((activeAlert: any) => { @@ -151,7 +151,7 @@ export default function bulkUntrackByQueryTests({ getService }: FtrProviderConte hits: { hits }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); hits.forEach((alert: any) => { diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/actions/execute_unsecured_action.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/actions/execute_unsecured_action.ts index 508dad042d8c5..07ce586fb6b18 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/actions/execute_unsecured_action.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/actions/execute_unsecured_action.ts @@ -7,7 +7,7 @@ import getPort from 'get-port'; import expect from '@kbn/expect'; -import type { SearchTotalHits } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchTotalHits } from '@elastic/elasticsearch/lib/api/types'; import { getWebhookServer } from '@kbn/actions-simulators-plugin/server/plugin'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { ObjectRemover } from '../../../common/lib'; @@ -274,54 +274,52 @@ export default function createUnsecuredActionTests({ getService }: FtrProviderCo function getEventLogExecuteQuery(start: string, actionId: string) { return { index: '.kibana-event-log*', - body: { - query: { - bool: { - filter: [ - { - term: { - 'event.provider': { - value: 'actions', - }, + query: { + bool: { + filter: [ + { + term: { + 'event.provider': { + value: 'actions', }, }, - { - term: { - 'event.action': 'execute', - }, + }, + { + term: { + 'event.action': 'execute', }, - { - range: { - '@timestamp': { - gte: start, - }, + }, + { + range: { + '@timestamp': { + gte: start, }, }, - { - nested: { - path: 'kibana.saved_objects', - query: { - bool: { - filter: [ - { - term: { - 'kibana.saved_objects.id': { - value: actionId, - }, + }, + { + nested: { + path: 'kibana.saved_objects', + query: { + bool: { + filter: [ + { + term: { + 'kibana.saved_objects.id': { + value: actionId, }, }, - { - term: { - 'kibana.saved_objects.type': 'action', - }, + }, + { + term: { + 'kibana.saved_objects.type': 'action', }, - ], - }, + }, + ], }, }, }, - ], - }, + }, + ], }, }, }; diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/actions/schedule_unsecured_action.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/actions/schedule_unsecured_action.ts index f740c82bcbd70..15fdac5f38eb3 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/actions/schedule_unsecured_action.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/actions/schedule_unsecured_action.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type { SearchTotalHits } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SearchTotalHits } from '@elastic/elasticsearch/lib/api/types'; import { Spaces } from '../../scenarios'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import { getUrlPrefix, ObjectRemover } from '../../../common/lib'; @@ -48,54 +48,52 @@ export default function createUnsecuredActionTests({ getService }: FtrProviderCo await retry.try(async () => { const searchResult = await es.search({ index: '.kibana-event-log*', - body: { - query: { - bool: { - filter: [ - { - term: { - 'event.provider': { - value: 'actions', - }, + query: { + bool: { + filter: [ + { + term: { + 'event.provider': { + value: 'actions', }, }, - { - term: { - 'event.action': 'execute', - }, + }, + { + term: { + 'event.action': 'execute', }, - { - range: { - '@timestamp': { - gte: testStart, - }, + }, + { + range: { + '@timestamp': { + gte: testStart, }, }, - { - nested: { - path: 'kibana.saved_objects', - query: { - bool: { - filter: [ - { - term: { - 'kibana.saved_objects.id': { - value: 'my-test-email', - }, + }, + { + nested: { + path: 'kibana.saved_objects', + query: { + bool: { + filter: [ + { + term: { + 'kibana.saved_objects.id': { + value: 'my-test-email', }, }, - { - term: { - 'kibana.saved_objects.type': 'action', - }, + }, + { + term: { + 'kibana.saved_objects.type': 'action', }, - ], - }, + }, + ], }, }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create_test_data.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create_test_data.ts index 87d676f46071a..9f257d2192edb 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create_test_data.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create_test_data.ts @@ -137,48 +137,46 @@ export async function createDataStream(es: Client, name: string) { // A data stream requires an index template before it can be created. await es.indices.putIndexTemplate({ name, - body: { - index_patterns: [name + '*'], - template: { - mappings: { - properties: { - '@timestamp': { - type: 'date', - }, - source: { - type: 'keyword', - }, - reference: { - type: 'keyword', - }, - params: { - enabled: false, - type: 'object', - }, - host: { - properties: { - hostname: { - type: 'text', - fields: { - keyword: { - type: 'keyword', - ignore_above: 256, - }, + index_patterns: [name + '*'], + template: { + mappings: { + properties: { + '@timestamp': { + type: 'date', + }, + source: { + type: 'keyword', + }, + reference: { + type: 'keyword', + }, + params: { + enabled: false, + type: 'object', + }, + host: { + properties: { + hostname: { + type: 'text', + fields: { + keyword: { + type: 'keyword', + ignore_above: 256, }, }, - id: { - type: 'keyword', - }, - name: { - type: 'keyword', - }, + }, + id: { + type: 'keyword', + }, + name: { + type: 'keyword', }, }, }, }, }, - data_stream: {}, }, + data_stream: {}, }); await es.indices.createDataStream({ name }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/alerts_base.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/alerts_base.ts index d1883b0be924a..9bc0a66b3163a 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/alerts_base.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/alerts_base.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { omit } from 'lodash'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Response as SupertestResponse } from 'supertest'; import { RecoveredActionGroup } from '@kbn/alerting-plugin/common'; import { TaskRunning, TaskRunningStage } from '@kbn/task-manager-plugin/server/task_running'; @@ -385,34 +385,32 @@ instanceStateValue: true TaskRunning >({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.status': 'idle', - }, + query: { + bool: { + must: [ + { + term: { + 'task.status': 'idle', }, - { - term: { - 'task.attempts': 1, - }, + }, + { + term: { + 'task.attempts': 1, }, - { - term: { - 'task.taskType': 'actions:test.rate-limit', - }, + }, + { + term: { + 'task.taskType': 'actions:test.rate-limit', }, - { - range: { - 'task.scheduledAt': { - gte: testStart, - }, + }, + { + range: { + 'task.scheduledAt': { + gte: testStart, }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts index 846c4a719522f..b4e7b8e497b83 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group1/disable.ts @@ -212,7 +212,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex hits: { hits: activeAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); expect(activeAlerts.length).eql(2); @@ -227,7 +227,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex hits: { hits: untrackedAlerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); expect(untrackedAlerts.length).eql(2); untrackedAlerts.forEach((untrackedAlert: any) => { diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/ml_rule_types/anomaly_detection/alert.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/ml_rule_types/anomaly_detection/alert.ts index 70664c3b37434..2f9e6225bd322 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/ml_rule_types/anomaly_detection/alert.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group2/ml_rule_types/anomaly_detection/alert.ts @@ -294,13 +294,13 @@ export default function alertTests({ getService }: FtrProviderContext) { docTime += step; } - const body = docs.flatMap(({ _index, ...doc }) => { + const operations = docs.flatMap(({ _index, ...doc }) => { return [{ index: { _index } }, doc]; }); await es.bulk({ refresh: 'wait_for', - body, + operations, }); log.debug('> docs ingested.'); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group3/maintenance_window_scoped_query.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group3/maintenance_window_scoped_query.ts index 2c43649eb7822..21355239ae64d 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group3/maintenance_window_scoped_query.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group3/maintenance_window_scoped_query.ts @@ -94,7 +94,7 @@ export default function maintenanceWindowScopedQueryTests({ getService }: FtrPro await retry.try(async () => { const result = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); expect(result.hits.hits[0]?._source?.[ALERT_MAINTENANCE_WINDOW_IDS]).eql([ diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_delay.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_delay.ts index 20f9901a53688..785ec9a946856 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_delay.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_delay.ts @@ -101,24 +101,22 @@ export default function createAlertDelayTests({ getService }: FtrProviderContext const result: any = await retry.try(async () => { const searchResult = await es.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.taskType': 'alerting:test.patternFiring', - }, + query: { + bool: { + must: [ + { + term: { + 'task.taskType': 'alerting:test.patternFiring', }, - { - range: { - 'task.scheduledAt': { - gte: start, - }, + }, + { + range: { + 'task.scheduledAt': { + gte: start, }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_severity.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_severity.ts index 533bd593e3588..877efc20494f7 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_severity.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alert_severity.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import type { Alert } from '@kbn/alerts-as-data-utils'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { ALERT_ACTION_GROUP, ALERT_SEVERITY_IMPROVING, @@ -115,7 +115,7 @@ export default function createAlertSeverityTests({ getService }: FtrProviderCont async function queryForAlertDocs(): Promise>> { const searchResult = await es.search({ index: alertsAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); return searchResult.hits.hits as Array>; } diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data.ts index 8833800f8215f..c141a4e0c8fcb 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { IValidatedEvent } from '@kbn/event-log-plugin/server'; import { setTimeout as setTimeoutAsync } from 'timers/promises'; import type { Alert } from '@kbn/alerts-as-data-utils'; @@ -539,7 +539,7 @@ export default function createAlertsAsDataInstallResourcesTest({ getService }: F async function queryForAlertDocs(): Promise>> { const searchResult = await es.search({ index: alertsAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); return searchResult.hits.hits as Array>; } diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_alert_delay.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_alert_delay.ts index 59068ee945ea2..5a7db5b2955bf 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_alert_delay.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_alert_delay.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { get } from 'lodash'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import { IValidatedEvent } from '@kbn/event-log-plugin/server'; import type { Alert } from '@kbn/alerts-as-data-utils'; import { @@ -563,7 +563,7 @@ export default function createAlertsAsDataAlertDelayInstallResourcesTest({ ): Promise>> { const searchResult = await es.search({ index, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); return searchResult.hits.hits as Array>; } diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_conflicts.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_conflicts.ts index 4866f8581f0bf..eb738e8a60dff 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_conflicts.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_conflicts.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { Client } from '@elastic/elasticsearch'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import type { Alert } from '@kbn/alerts-as-data-utils'; import { ESTestIndexTool } from '@kbn/alerting-api-integration-helpers'; import { basename } from 'node:path'; @@ -196,11 +196,9 @@ export default function createAlertsAsDataInstallResourcesTest({ getService }: F const searchResult = await es.search({ index, size: count, - body: { - query: { - bool: { - must: [{ term: { 'kibana.alert.rule.uuid': ruleId } }], - }, + query: { + bool: { + must: [{ term: { 'kibana.alert.rule.uuid': ruleId } }], }, }, }); @@ -256,8 +254,7 @@ function compareAlertDocs( // perform an adhoc update to an alert doc async function adHocUpdate(es: Client, index: string, id: string) { - const body = { doc: DocUpdate }; - await es.update({ index, id, body, refresh: true }); + await es.update({ index, id, doc: DocUpdate, refresh: true }); } // we'll do the adhoc updates with this data diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_flapping.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_flapping.ts index 9bab20d763fcb..0d9c2654a8614 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_flapping.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/alerts_as_data/alerts_as_data_flapping.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchHit } from '@elastic/elasticsearch/lib/api/types'; import type { Alert } from '@kbn/alerts-as-data-utils'; import { RuleNotifyWhen } from '@kbn/alerting-plugin/common'; import { setTimeout as setTimeoutAsync } from 'timers/promises'; @@ -758,18 +758,16 @@ export default function createAlertsAsDataFlappingTest({ getService }: FtrProvid async function queryForAlertDocs(ruleId: string): Promise>> { const searchResult = await es.search({ index: alertsAsDataIndex, - body: { - sort: [ - { - '@timestamp': 'desc', - }, - ], - query: { - bool: { - must: { - term: { - [ALERT_RULE_UUID]: { value: ruleId }, - }, + sort: [ + { + '@timestamp': 'desc', + }, + ], + query: { + bool: { + must: { + term: { + [ALERT_RULE_UUID]: { value: ruleId }, }, }, }, diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/builtin_alert_types/circuit_breaker/alert_limit_services.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/builtin_alert_types/circuit_breaker/alert_limit_services.ts index 3d5eb4004ca94..bc8606bc160f8 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/builtin_alert_types/circuit_breaker/alert_limit_services.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/builtin_alert_types/circuit_breaker/alert_limit_services.ts @@ -61,7 +61,7 @@ export default function maxAlertsRuleTests({ getService }: FtrProviderContext) { // check there are no docs written out in the ES_TEST_INDEX const results = await es.search( - { index: ES_TEST_INDEX_NAME, body: { query: { match_all: {} } } }, + { index: ES_TEST_INDEX_NAME, query: { match_all: {} } }, { meta: true } ); // @ts-expect-error doesn't handle total: number @@ -98,7 +98,7 @@ export default function maxAlertsRuleTests({ getService }: FtrProviderContext) { // check there are docs written out in the ES_TEST_INDEX const results = await es.search( - { index: ES_TEST_INDEX_NAME, body: { query: { match_all: {} } } }, + { index: ES_TEST_INDEX_NAME, query: { match_all: {} } }, { meta: true } ); // @ts-expect-error doesn't handle total: number @@ -140,7 +140,7 @@ export default function maxAlertsRuleTests({ getService }: FtrProviderContext) { // check there are docs written out in the ES_TEST_INDEX const results = await es.search( - { index: ES_TEST_INDEX_NAME, body: { query: { match_all: {} } } }, + { index: ES_TEST_INDEX_NAME, query: { match_all: {} } }, { meta: true } ); // @ts-expect-error doesn't handle total: number diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_disable.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_disable.ts index 8cf9de5fd3057..2332f99c1d960 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_disable.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/bulk_disable.ts @@ -50,7 +50,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex hits: { hits: alerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); return alerts; diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/flapping_history.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/flapping_history.ts index 2fa1868591174..eaa170f0a870b 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/flapping_history.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/flapping_history.ts @@ -135,24 +135,22 @@ export default function createFlappingHistoryTests({ getService }: FtrProviderCo const result: any = await retry.try(async () => { const searchResult = await es.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.taskType': 'alerting:test.patternFiring', - }, + query: { + bool: { + must: [ + { + term: { + 'task.taskType': 'alerting:test.patternFiring', }, - { - range: { - 'task.scheduledAt': { - gte: start, - }, + }, + { + range: { + 'task.scheduledAt': { + gte: start, }, }, - ], - }, + }, + ], }, }, }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts index 2cb5a616320eb..ba13298ae6dc8 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/migrations.ts @@ -6,7 +6,7 @@ */ import expect from 'expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { RawRule, RawRuleAction } from '@kbn/alerting-plugin/server/types'; import { FILEBEAT_7X_INDICATOR_PATH } from '@kbn/alerting-plugin/server/saved_objects/migrations'; import type { SavedObjectReference } from '@kbn/core/server'; @@ -211,11 +211,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { const searchResult = await es.search<{ alert: RawRule }>( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - _id: 'alert:74f3e6d7-b7bb-477d-ac28-92ee22728e6e', - }, + query: { + term: { + _id: 'alert:74f3e6d7-b7bb-477d-ac28-92ee22728e6e', }, }, }, @@ -231,11 +229,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { const searchResult = await es.search<{ alert: RawRule; references: {} }>( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - _id: 'alert:9c003b00-00ee-11ec-b067-2524946ba327', - }, + query: { + term: { + _id: 'alert:9c003b00-00ee-11ec-b067-2524946ba327', }, }, }, @@ -449,11 +445,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { const searchResult = await es.search<{ alert: RawRule }>( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - _id: 'alert:4d973df0-23df-11ed-8ae4-e988ad0f6fa7', - }, + query: { + term: { + _id: 'alert:4d973df0-23df-11ed-8ae4-e988ad0f6fa7', }, }, }, @@ -588,17 +582,15 @@ export default function createGetTests({ getService }: FtrProviderContext) { const response = await es.search<{ alert: RawRule }>( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - bool: { - must: [ - { - term: { - 'alert.alertTypeId': '.es-query', - }, + query: { + bool: { + must: [ + { + term: { + 'alert.alertTypeId': '.es-query', }, - ], - }, + }, + ], }, }, }, @@ -699,7 +691,7 @@ export default function createGetTests({ getService }: FtrProviderContext) { const { docs } = await es.mget<{ alert: RawRule }>({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { ids: [securityCustomRuleId, securityImmutableRuleId, nonSecurityRuleId] }, + ids: [securityCustomRuleId, securityImmutableRuleId, nonSecurityRuleId], }); const securityCustomRuleMuteAll = diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts index 475a36872e8c7..fad5291d69f5d 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/muted_alerts.ts @@ -51,7 +51,7 @@ export default function createDisableRuleTests({ getService }: FtrProviderContex hits: { hits: alerts }, } = await es.search({ index: alertAsDataIndex, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); return alerts; diff --git a/x-pack/test/api_integration/apis/entity_manager/helpers/data_generation.ts b/x-pack/test/api_integration/apis/entity_manager/helpers/data_generation.ts index 2f784e6a75533..a78c0aae7066e 100644 --- a/x-pack/test/api_integration/apis/entity_manager/helpers/data_generation.ts +++ b/x-pack/test/api_integration/apis/entity_manager/helpers/data_generation.ts @@ -27,12 +27,12 @@ export async function createIndexWithDocuments( }, }); - const bulkActions = options.documents.flatMap((doc) => { + const operations = options.documents.flatMap((doc) => { return [{ create: { _index: options.index } }, doc]; }); await client.bulk({ - body: bulkActions, + operations, refresh: 'wait_for', }); diff --git a/x-pack/test/api_integration/apis/es/has_privileges.ts b/x-pack/test/api_integration/apis/es/has_privileges.ts index 4cd1f70d4fffc..e62bdfe309b98 100644 --- a/x-pack/test/api_integration/apis/es/has_privileges.ts +++ b/x-pack/test/api_integration/apis/es/has_privileges.ts @@ -30,28 +30,23 @@ export default function ({ getService }: FtrProviderContext) { await es.security.putRole({ name: 'hp_read_user', - body: { - cluster: [], - // @ts-expect-error unknown property - index: [], - applications: [ - { - application, - privileges: ['read'], - resources: ['*'], - }, - ], - }, + cluster: [], + body: { index: [] }, + applications: [ + { + application, + privileges: ['read'], + resources: ['*'], + }, + ], }); await es.security.putUser({ username: 'testuser', - body: { - password: 'testpassword', - roles: ['hp_read_user'], - full_name: 'a kibana user', - email: 'a_kibana_rbac_user@elastic.co', - }, + password: 'testpassword', + roles: ['hp_read_user'], + full_name: 'a kibana user', + email: 'a_kibana_rbac_user@elastic.co', }); }); diff --git a/x-pack/test/api_integration/apis/management/index_lifecycle_management/lib/elasticsearch.js b/x-pack/test/api_integration/apis/management/index_lifecycle_management/lib/elasticsearch.js index 8c5481a6e2c85..6b05cbe8b4e80 100644 --- a/x-pack/test/api_integration/apis/management/index_lifecycle_management/lib/elasticsearch.js +++ b/x-pack/test/api_integration/apis/management/index_lifecycle_management/lib/elasticsearch.js @@ -37,7 +37,7 @@ export const initElasticsearchHelpers = (getService) => { // Data streams const createDataStream = (dataStream = getRandomString(), document) => { dataStreamsCreated.push(dataStream); - return es.index({ index: dataStream, body: document }, { meta: true }); + return es.index({ index: dataStream, document }, { meta: true }); }; const deleteDataStream = (dataStream) => { diff --git a/x-pack/test/api_integration/apis/management/index_management/component_templates.ts b/x-pack/test/api_integration/apis/management/index_management/component_templates.ts index e325f4bbfa588..547be629c6a5f 100644 --- a/x-pack/test/api_integration/apis/management/index_management/component_templates.ts +++ b/x-pack/test/api_integration/apis/management/index_management/component_templates.ts @@ -145,7 +145,6 @@ export default function ({ getService }: FtrProviderContext) { }, }, lifecycle: { - // @ts-expect-error @elastic/elasticsearch enabled prop is still not in the ES types enabled: true, data_retention: '2d', }, diff --git a/x-pack/test/api_integration/apis/management/index_management/create_enrich_policy.ts b/x-pack/test/api_integration/apis/management/index_management/create_enrich_policy.ts index 36f5e17e347d0..07606931bb1d8 100644 --- a/x-pack/test/api_integration/apis/management/index_management/create_enrich_policy.ts +++ b/x-pack/test/api_integration/apis/management/index_management/create_enrich_policy.ts @@ -27,30 +27,26 @@ export default function ({ getService }: FtrProviderContext) { try { await es.indices.create({ index: INDEX_A_NAME, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - firstName: { - type: 'text', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + firstName: { + type: 'text', }, }, }, }); await es.indices.create({ index: INDEX_B_NAME, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - age: { - type: 'long', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + age: { + type: 'long', }, }, }, @@ -62,10 +58,8 @@ export default function ({ getService }: FtrProviderContext) { try { await es.indices.putIndexTemplate({ name: DATA_STREAM_TEMPLATE, - body: { - index_patterns: ['data-stream-*'], - data_stream: {}, - }, + index_patterns: ['data-stream-*'], + data_stream: {}, }); await es.indices.createDataStream({ name: DATA_STREAM_A_NAME, diff --git a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts index 25797d52e03cc..e95f8a4449daa 100644 --- a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts +++ b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts @@ -210,17 +210,15 @@ export default function ({ getService }: FtrProviderContext) { logsdbSettings.forEach(({ enabled, prior_logs_usage, indexMode }) => { it(`returns ${indexMode} index mode if logsdb.enabled setting is ${enabled} and logs.prior_logs_usage is ${prior_logs_usage}`, async () => { await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - logsdb: { - enabled, - }, - }, + persistent: { + cluster: { logsdb: { - prior_logs_usage, + enabled, }, }, + logsdb: { + prior_logs_usage, + }, }, }); diff --git a/x-pack/test/api_integration/apis/management/index_management/lib/datastreams.helpers.ts b/x-pack/test/api_integration/apis/management/index_management/lib/datastreams.helpers.ts index 944c679c3205f..dbaa77e61c338 100644 --- a/x-pack/test/api_integration/apis/management/index_management/lib/datastreams.helpers.ts +++ b/x-pack/test/api_integration/apis/management/index_management/lib/datastreams.helpers.ts @@ -15,29 +15,26 @@ export function datastreamsHelpers(getService: FtrProviderContext['getService']) // A data stream requires an index template before it can be created. await es.indices.putIndexTemplate({ name, - body: { - // We need to match the names of backing indices with this template. - index_patterns: [name + '*'], - template: { - mappings: { - properties: { - '@timestamp': { - type: 'date', - }, + // We need to match the names of backing indices with this template. + index_patterns: [name + '*'], + template: { + mappings: { + properties: { + '@timestamp': { + type: 'date', }, }, - settings: { - index: { - mode: indexMode, - }, - }, - lifecycle: { - // @ts-expect-error @elastic/elasticsearch enabled prop is not typed yet - enabled: true, + }, + settings: { + index: { + mode: indexMode, }, }, - data_stream: {}, + lifecycle: { + enabled: true, + }, }, + data_stream: {}, }); await es.indices.createDataStream({ name }); @@ -46,14 +43,12 @@ export function datastreamsHelpers(getService: FtrProviderContext['getService']) const updateIndexTemplateMappings = async (name: string, mappings: any) => { await es.indices.putIndexTemplate({ name, - body: { - // We need to match the names of backing indices with this template. - index_patterns: [name + '*'], - template: { - mappings, - }, - data_stream: {}, + // We need to match the names of backing indices with this template. + index_patterns: [name + '*'], + template: { + mappings, }, + data_stream: {}, }); }; diff --git a/x-pack/test/api_integration/apis/management/index_management/lib/enrich_policies.helpers.ts b/x-pack/test/api_integration/apis/management/index_management/lib/enrich_policies.helpers.ts index 9a4288716c4e4..f4063346bc128 100644 --- a/x-pack/test/api_integration/apis/management/index_management/lib/enrich_policies.helpers.ts +++ b/x-pack/test/api_integration/apis/management/index_management/lib/enrich_policies.helpers.ts @@ -24,15 +24,13 @@ export function enrichPoliciesHelpers(getService: FtrProviderContext['getService const createIndex = async (indexName: string) => { await es.indices.create({ index: indexName, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - firstName: { - type: 'text', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + firstName: { + type: 'text', }, }, }, diff --git a/x-pack/test/api_integration/apis/management/index_management/templates.ts b/x-pack/test/api_integration/apis/management/index_management/templates.ts index 49ed3dfb7158d..0f40aca667de9 100644 --- a/x-pack/test/api_integration/apis/management/index_management/templates.ts +++ b/x-pack/test/api_integration/apis/management/index_management/templates.ts @@ -263,17 +263,15 @@ export default function ({ getService }: FtrProviderContext) { logsdbSettings.forEach(({ enabled, prior_logs_usage, indexMode }) => { it(`returns ${indexMode} index mode if logsdb.enabled setting is ${enabled}`, async () => { await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - logsdb: { - enabled, - }, - }, + persistent: { + cluster: { logsdb: { - prior_logs_usage, + enabled, }, }, + logsdb: { + prior_logs_usage, + }, }, }); diff --git a/x-pack/test/api_integration/apis/management/rollup/rollup.js b/x-pack/test/api_integration/apis/management/rollup/rollup.js index 16e7921ff1c2e..1048e5141996d 100644 --- a/x-pack/test/api_integration/apis/management/rollup/rollup.js +++ b/x-pack/test/api_integration/apis/management/rollup/rollup.js @@ -134,10 +134,16 @@ export default function ({ getService }) { }); it('should handle ES errors', async () => { - const payload = { job: { id: 'abc', invalid: 'property' } }; + const payload = { + job: { id: 'abc', ...getJobPayload(indexName).job, invalid: 'property' }, + }; const { body } = await createJob(payload); - expect(body.message).to.contain('unknown field [invalid]'); + // expect(body.message).to.contain('unknown field [invalid]'); + // elasticsearch@9.0.0 https://github.com/elastic/elasticsearch-js/issues/2584 + // At the moment, the client places unknown fields as URL parameters, we are discussing changing that to use the body as a catch-all. + // This might revert the asssertion to the above. + expect(body.message).to.contain('contains unrecognized parameter: [invalid]'); }); it('should list the newly created job', async () => { diff --git a/x-pack/test/api_integration/apis/maps/maps_telemetry.ts b/x-pack/test/api_integration/apis/maps/maps_telemetry.ts index 3207fdbb739ef..683cf0851158c 100644 --- a/x-pack/test/api_integration/apis/maps/maps_telemetry.ts +++ b/x-pack/test/api_integration/apis/maps/maps_telemetry.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { ELASTIC_HTTP_VERSION_HEADER, X_ELASTIC_INTERNAL_ORIGIN_REQUEST, diff --git a/x-pack/test/api_integration/apis/metrics_ui/metric_threshold_alert.ts b/x-pack/test/api_integration/apis/metrics_ui/metric_threshold_alert.ts index b91a2185eb728..882219a49e8e2 100644 --- a/x-pack/test/api_integration/apis/metrics_ui/metric_threshold_alert.ts +++ b/x-pack/test/api_integration/apis/metrics_ui/metric_threshold_alert.ts @@ -1359,7 +1359,7 @@ export default function ({ getService }: FtrProviderContext) { before(async () => { await esClient.index({ index, - body: {}, + document: {}, }); }); const aggs = ['avg', 'min', 'max', 'rate', 'cardinality', 'count']; @@ -1379,7 +1379,7 @@ export default function ({ getService }: FtrProviderContext) { ); const result = await esClient.search({ index, - body: searchBody, + ...searchBody, }); expect(result.hits).to.be.ok(); @@ -1403,7 +1403,7 @@ export default function ({ getService }: FtrProviderContext) { ); const result = await esClient.search({ index, - body: searchBody, + ...searchBody, }); expect(result.hits).to.be.ok(); @@ -1427,7 +1427,7 @@ export default function ({ getService }: FtrProviderContext) { ); const result = await esClient.search({ index, - body: searchBody, + ...searchBody, }); expect(result.hits).to.be.ok(); @@ -1450,7 +1450,7 @@ export default function ({ getService }: FtrProviderContext) { ); const result = await esClient.search({ index, - body: searchBody, + ...searchBody, }); expect(result.hits).to.be.ok(); diff --git a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts index e0cf79ae7ba83..635da321c7bf4 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { Calendar } from '@kbn/ml-plugin/server/models/calendar'; type ScheduledEvent = estypes.MlCalendarEvent; diff --git a/x-pack/test/api_integration/apis/ml/datafeeds/update.ts b/x-pack/test/api_integration/apis/ml/datafeeds/update.ts index dabf2deb1de67..f373f6a5c45e4 100644 --- a/x-pack/test/api_integration/apis/ml/datafeeds/update.ts +++ b/x-pack/test/api_integration/apis/ml/datafeeds/update.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; @@ -29,12 +29,12 @@ export default ({ getService }: FtrProviderContext) => { expectedStatusCode: number, space?: string ) { - const datafeedId = datafeedConfig.datafeed_id; + const { datafeed_id: datafeedId, ...requestBody } = datafeedConfig; const { body, status } = await supertest .post(`${space ? `/s/${space}` : ''}/internal/ml/datafeeds/${datafeedId}/_update`) .auth(user, ml.securityCommon.getPasswordForUser(user)) .set(getCommonRequestHeader('1')) - .send(datafeedConfig.body); + .send(requestBody); ml.api.assertResponseStatusCode(expectedStatusCode, status, body); return body; @@ -62,7 +62,7 @@ export default ({ getService }: FtrProviderContext) => { it('should update datafeed with correct space', async () => { await updateDatafeed( - { datafeed_id: datafeedIdSpace1, body: { query_delay: newQueryDelay } }, + { datafeed_id: datafeedIdSpace1, query_delay: newQueryDelay }, USER.ML_POWERUSER_ALL_SPACES, 200, idSpace1 @@ -79,7 +79,7 @@ export default ({ getService }: FtrProviderContext) => { it('should not update datafeed with incorrect space', async () => { await updateDatafeed( - { datafeed_id: datafeedIdSpace1, body: { query_delay: newQueryDelay } }, + { datafeed_id: datafeedIdSpace1, query_delay: newQueryDelay }, USER.ML_POWERUSER_ALL_SPACES, 404, idSpace2 @@ -88,7 +88,7 @@ export default ({ getService }: FtrProviderContext) => { it('should not be updatable by ml viewer user', async () => { await updateDatafeed( - { datafeed_id: datafeedIdSpace1, body: { query_delay: newQueryDelay } }, + { datafeed_id: datafeedIdSpace1, query_delay: newQueryDelay }, USER.ML_VIEWER_ALL_SPACES, 403, idSpace1 diff --git a/x-pack/test/api_integration/apis/ml/job_audit_messages/index.ts b/x-pack/test/api_integration/apis/ml/job_audit_messages/index.ts index d66728613a1cd..12fda0acd399d 100644 --- a/x-pack/test/api_integration/apis/ml/job_audit_messages/index.ts +++ b/x-pack/test/api_integration/apis/ml/job_audit_messages/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { MlJob } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { MlJob } from '@elastic/elasticsearch/lib/api/types'; import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ loadTestFile }: FtrProviderContext) { diff --git a/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts b/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts index a392ea9751ba0..fd8afaf9cc2ef 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/datafeed_preview_validation.ts @@ -12,7 +12,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs.ts index a6c423bd8474d..7d470f540aac0 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs.ts @@ -159,7 +159,7 @@ export default ({ getService }: FtrProviderContext) => { expectedJobProperties[i].modelBytes, `model_bytes should be equal to ${JSON.stringify(expectedJobProperties[i].modelBytes)})` ); - expect(job.datafeed_config.timing_stats.total_search_time_ms).to.eql( + expect(job.datafeed_config.timing_stats?.total_search_time_ms).to.eql( expectedJobProperties[i].datafeedTotalSearchTimeMs, `datafeed total_search_time_ms should be equal to ${JSON.stringify( expectedJobProperties[i].datafeedTotalSearchTimeMs @@ -203,7 +203,7 @@ export default ({ getService }: FtrProviderContext) => { expectedJobPropertiesWithSpace[i].modelBytes )})` ); - expect(job.datafeed_config.timing_stats.total_search_time_ms).to.eql( + expect(job.datafeed_config.timing_stats?.total_search_time_ms).to.eql( expectedJobPropertiesWithSpace[i].datafeedTotalSearchTimeMs, `datafeed total_search_time_ms should be equal to ${JSON.stringify( expectedJobPropertiesWithSpace[i].datafeedTotalSearchTimeMs diff --git a/x-pack/test/api_integration/apis/ml/trained_models/model_downloads.ts b/x-pack/test/api_integration/apis/ml/trained_models/model_downloads.ts index 654d3ad472e8c..3d78b9b8e1070 100644 --- a/x-pack/test/api_integration/apis/ml/trained_models/model_downloads.ts +++ b/x-pack/test/api_integration/apis/ml/trained_models/model_downloads.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { type NodesInfoNodeInfo } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { type NodesInfoNodeInfo } from '@elastic/elasticsearch/lib/api/types'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; import { getCommonRequestHeader } from '../../../../functional/services/ml/common_api'; diff --git a/x-pack/test/api_integration/apis/ml/trained_models/start_stop_deployment.ts b/x-pack/test/api_integration/apis/ml/trained_models/start_stop_deployment.ts index debbba310fad1..6ef0a915a2c4b 100644 --- a/x-pack/test/api_integration/apis/ml/trained_models/start_stop_deployment.ts +++ b/x-pack/test/api_integration/apis/ml/trained_models/start_stop_deployment.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type { MlGetTrainedModelsStatsResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MlGetTrainedModelsStatsResponse } from '@elastic/elasticsearch/lib/api/types'; import { SUPPORTED_TRAINED_MODELS } from '../../../../functional/services/ml/api'; import { FtrProviderContext } from '../../../ftr_provider_context'; import { USER } from '../../../../functional/services/ml/security_common'; @@ -83,7 +83,7 @@ export default ({ getService }: FtrProviderContext) => { statsResponse as MlGetTrainedModelsStatsResponse ).trained_model_stats.find((v) => v.deployment_stats?.deployment_id === testModel.id); - expect(modelStats!.deployment_stats!.allocation_status.state).to.match( + expect(modelStats!.deployment_stats!.allocation_status?.state).to.match( /\bstarted\b|\bfully_allocated\b/ ); }); @@ -110,7 +110,7 @@ export default ({ getService }: FtrProviderContext) => { statsResponse as MlGetTrainedModelsStatsResponse ).trained_model_stats.find((v) => v.deployment_stats?.deployment_id === customDeploymentId); - expect(modelStats!.deployment_stats!.allocation_status.state).to.match( + expect(modelStats!.deployment_stats!.allocation_status?.state).to.match( /\bstarted\b|\bfully_allocated\b/ ); }); @@ -141,7 +141,7 @@ export default ({ getService }: FtrProviderContext) => { statsResponse as MlGetTrainedModelsStatsResponse ).trained_model_stats.find((v) => v.deployment_stats?.deployment_id === testModel.id); - expect(modelStats!.deployment_stats!.allocation_status.state).to.match( + expect(modelStats!.deployment_stats!.allocation_status?.state).to.match( /\bstarted\b|\bfully_allocated\b/ ); }); diff --git a/x-pack/test/api_integration/apis/search/search.ts b/x-pack/test/api_integration/apis/search/search.ts index 3a6ced441d02a..b55f43715c1df 100644 --- a/x-pack/test/api_integration/apis/search/search.ts +++ b/x-pack/test/api_integration/apis/search/search.ts @@ -45,7 +45,7 @@ export default function ({ getService }: FtrProviderContext) { await es.index({ index: 'search-api-test', id: 'search-api-test-doc', - body: { message: 'test doc' }, + document: { message: 'test doc' }, refresh: 'wait_for', }); }); @@ -395,7 +395,12 @@ export default function ({ getService }: FtrProviderContext) { }, }) .expect(400); - verifyErrorResponse(resp.body, 400, 'illegal_argument_exception', true); + verifyErrorResponse( + resp.body, + 400, + '"params.index" is required when performing a rollup search', + false + ); }); it('should return 400 if rollup search is without non-existent index', async () => { diff --git a/x-pack/test/api_integration/apis/security/query_api_keys.ts b/x-pack/test/api_integration/apis/security/query_api_keys.ts index 551b28ed8ebc0..37b1668a03863 100644 --- a/x-pack/test/api_integration/apis/security/query_api_keys.ts +++ b/x-pack/test/api_integration/apis/security/query_api_keys.ts @@ -88,7 +88,7 @@ export default function ({ getService }: FtrProviderContext) { const cleanup = async () => { await getService('es').deleteByQuery({ index: '.security-7', - body: { query: { match: { doc_type: 'api_key' } } }, + query: { match: { doc_type: 'api_key' } }, refresh: true, }); }; diff --git a/x-pack/test/api_integration/apis/security/roles.ts b/x-pack/test/api_integration/apis/security/roles.ts index 80e07b69f98df..723e24001baf0 100644 --- a/x-pack/test/api_integration/apis/security/roles.ts +++ b/x-pack/test/api_integration/apis/security/roles.ts @@ -129,16 +129,14 @@ export default function ({ getService }: FtrProviderContext) { it('should fail when role already exists', async () => { await es.security.putRole({ name: 'test_role', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - run_as: ['reporting_user'], - }, + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + run_as: ['reporting_user'], }); await supertest @@ -162,30 +160,28 @@ export default function ({ getService }: FtrProviderContext) { it('should update a role with elasticsearch, kibana and other applications privileges', async () => { await es.security.putRole({ name: 'role_to_update', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'logstash-default', - privileges: ['logstash-privilege'], - resources: ['*'], - }, - ], - run_as: ['reporting_user'], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], }, + { + application: 'logstash-default', + privileges: ['logstash-privilege'], + resources: ['*'], + }, + ], + run_as: ['reporting_user'], + metadata: { + bar: 'old-metadata', }, }); @@ -266,16 +262,14 @@ export default function ({ getService }: FtrProviderContext) { when using ${basic ? 'basic' : 'trial'} license`, async () => { await es.security.putRole({ name: 'role_to_update_with_dls_fls', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - run_as: ['reporting_user'], - }, + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + run_as: ['reporting_user'], }); await supertest @@ -319,43 +313,41 @@ export default function ({ getService }: FtrProviderContext) { it('should get roles', async () => { await es.security.putRole({ name: 'role_to_get', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - allow_restricted_indices: false, - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'kibana-.kibana', - privileges: [ - 'feature_dashboard_v2.read', - 'feature_discover_v2.all', - 'feature_ml.all', - ], - resources: ['space:marketing', 'space:sales'], - }, - { - application: 'logstash-default', - privileges: ['logstash-privilege'], - resources: ['*'], - }, - ], - run_as: ['watcher_user'], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], + allow_restricted_indices: false, }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], + }, + { + application: 'kibana-.kibana', + privileges: [ + 'feature_dashboard_v2.read', + 'feature_discover_v2.all', + 'feature_ml.all', + ], + resources: ['space:marketing', 'space:sales'], }, + { + application: 'logstash-default', + privileges: ['logstash-privilege'], + resources: ['*'], + }, + ], + run_as: ['watcher_user'], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); @@ -404,65 +396,61 @@ export default function ({ getService }: FtrProviderContext) { it('should get roles by space id', async () => { await es.security.putRole({ name: 'space_role_not_to_get', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - allow_restricted_indices: false, - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: [ - 'feature_dashboard_v2.read', - 'feature_discover_v2.all', - 'feature_ml.all', - ], - resources: ['space:marketing', 'space:sales'], - }, - ], - run_as: ['watcher_user'], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], + allow_restricted_indices: false, }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: [ + 'feature_dashboard_v2.read', + 'feature_discover_v2.all', + 'feature_ml.all', + ], + resources: ['space:marketing', 'space:sales'], }, + ], + run_as: ['watcher_user'], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); await es.security.putRole({ name: 'space_role_to_get', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - allow_restricted_indices: false, - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: [ - 'feature_dashboard_v2.read', - 'feature_discover_v2.all', - 'feature_ml.all', - ], - resources: ['space:engineering', 'space:sales'], - }, - ], - run_as: ['watcher_user'], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], + allow_restricted_indices: false, }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: [ + 'feature_dashboard_v2.read', + 'feature_discover_v2.all', + 'feature_ml.all', + ], + resources: ['space:engineering', 'space:sales'], }, + ], + run_as: ['watcher_user'], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); @@ -540,39 +528,37 @@ export default function ({ getService }: FtrProviderContext) { it('should query roles by name', async () => { await es.security.putRole({ name: 'role_to_query', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - allow_restricted_indices: false, - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'kibana-.kibana', - privileges: ['feature_dashboard.read', 'feature_discover.all', 'feature_ml.all'], - resources: ['space:marketing', 'space:sales'], - }, - { - application: 'logstash-default', - privileges: ['logstash-privilege'], - resources: ['*'], - }, - ], - run_as: ['watcher_user'], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], + allow_restricted_indices: false, }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], + }, + { + application: 'kibana-.kibana', + privileges: ['feature_dashboard.read', 'feature_discover.all', 'feature_ml.all'], + resources: ['space:marketing', 'space:sales'], }, + { + application: 'logstash-default', + privileges: ['logstash-privilege'], + resources: ['*'], + }, + ], + run_as: ['watcher_user'], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); diff --git a/x-pack/test/api_integration/apis/security/roles_bulk.ts b/x-pack/test/api_integration/apis/security/roles_bulk.ts index 0415bc66c98ca..22c63e3ec1542 100644 --- a/x-pack/test/api_integration/apis/security/roles_bulk.ts +++ b/x-pack/test/api_integration/apis/security/roles_bulk.ts @@ -275,30 +275,28 @@ export default function ({ getService }: FtrProviderContext) { it('should update roles with elasticsearch, kibana and other applications privileges', async () => { await es.security.putRole({ name: 'bulk_role_to_update_1', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'logstash-default', - privileges: ['logstash-privilege'], - resources: ['*'], - }, - ], - run_as: ['reporting_user'], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], + }, + { + application: 'logstash-default', + privileges: ['logstash-privilege'], + resources: ['*'], }, + ], + run_as: ['reporting_user'], + metadata: { + bar: 'old-metadata', }, }); await es.security.putRole({ name: 'bulk_role_to_update_2', body: {} }); diff --git a/x-pack/test/api_integration/apis/slos/helper/es.ts b/x-pack/test/api_integration/apis/slos/helper/es.ts index eed0df0430e07..190f9b08bd9af 100644 --- a/x-pack/test/api_integration/apis/slos/helper/es.ts +++ b/x-pack/test/api_integration/apis/slos/helper/es.ts @@ -16,18 +16,16 @@ export class SloEsClient { public async getSLOSummaryDataById(id: string) { return await this.esClient.search({ index: SUMMARY_DESTINATION_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - { - term: { 'slo.id': id }, - }, - { - term: { isTempDoc: false }, - }, - ], - }, + query: { + bool: { + filter: [ + { + term: { 'slo.id': id }, + }, + { + term: { isTempDoc: false }, + }, + ], }, }, }); @@ -36,15 +34,13 @@ export class SloEsClient { public async getSLORollupDataById(id: string) { return await this.esClient.search({ index: SLI_DESTINATION_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - { - term: { 'slo.id': id }, - }, - ], - }, + query: { + bool: { + filter: [ + { + term: { 'slo.id': id }, + }, + ], }, }, }); diff --git a/x-pack/test/api_integration/apis/slos/helper/wait_for_index_state.ts b/x-pack/test/api_integration/apis/slos/helper/wait_for_index_state.ts index 45e301a1a25fb..c66361773ec2e 100644 --- a/x-pack/test/api_integration/apis/slos/helper/wait_for_index_state.ts +++ b/x-pack/test/api_integration/apis/slos/helper/wait_for_index_state.ts @@ -6,10 +6,7 @@ */ import type { Client } from '@elastic/elasticsearch'; -import type { - AggregationsAggregate, - SearchResponse, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsAggregate, SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { retryForSuccess } from '@kbn/ftr-common-functional-services'; import { ToolingLog } from '@kbn/tooling-log'; diff --git a/x-pack/test/api_integration/apis/telemetry/telemetry_local.ts b/x-pack/test/api_integration/apis/telemetry/telemetry_local.ts index 47f6fba85af88..c192963605979 100644 --- a/x-pack/test/api_integration/apis/telemetry/telemetry_local.ts +++ b/x-pack/test/api_integration/apis/telemetry/telemetry_local.ts @@ -46,7 +46,7 @@ export default function ({ getService }: FtrProviderContext) { let stats: Record; before('disable monitoring and pull local stats', async () => { - await es.cluster.putSettings({ body: disableCollection }); + await es.cluster.putSettings(disableCollection); await new Promise((r) => setTimeout(r, 1000)); const { body } = await supertest diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/cloud_backup_status.ts b/x-pack/test/api_integration/apis/upgrade_assistant/cloud_backup_status.ts index 5730403c9a1ee..a99070a5976d8 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/cloud_backup_status.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/cloud_backup_status.ts @@ -35,11 +35,9 @@ export default function ({ getService }: FtrProviderContext) { snapshot: snapshotName, wait_for_completion: true, // Configure snapshot so no indices are captured, so the request completes ASAP. - body: { - indices: 'this_index_doesnt_exist', - ignore_unavailable: true, - include_global_state: false, - }, + indices: 'this_index_doesnt_exist', + ignore_unavailable: true, + include_global_state: false, }); }; diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/cluster_settings.ts b/x-pack/test/api_integration/apis/upgrade_assistant/cluster_settings.ts index a0c138e7e3ab4..419643719f120 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/cluster_settings.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/cluster_settings.ts @@ -21,13 +21,11 @@ export default function ({ getService }: FtrProviderContext) { try { // Configure some deprecated cluster settings await es.cluster.putSettings({ - body: { - persistent: { - 'cluster.routing.allocation.exclude._tier': 'data_cold', - }, - transient: { - 'cluster.routing.allocation.include._tier': 'data_hot', - }, + persistent: { + 'cluster.routing.allocation.exclude._tier': 'data_cold', + }, + transient: { + 'cluster.routing.allocation.include._tier': 'data_hot', }, }); } catch (e) { diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts b/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts index ec2454fdea143..5c782ff1a6a22 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/es_deprecation_logs.helpers.ts @@ -44,12 +44,12 @@ export const initHelpers = (getService: FtrProviderContext['getService']) => { const createDeprecationLog = async (isElasticProduct = false) => { const id = getRandomString(); - const body = { + const document = { ...deprecationMock, }; if (isElasticProduct) { - (body as any)[DEPRECATION_LOGS_ORIGIN_FIELD] = 'kibana'; + (document as any)[DEPRECATION_LOGS_ORIGIN_FIELD] = 'kibana'; } await es.index({ @@ -57,7 +57,7 @@ export const initHelpers = (getService: FtrProviderContext['getService']) => { index: DEPRECATION_LOGS_INDEX, op_type: 'create', refresh: true, - body, + document, }); return id; @@ -67,10 +67,8 @@ export const initHelpers = (getService: FtrProviderContext['getService']) => { return await es.deleteByQuery({ index: DEPRECATION_LOGS_INDEX, refresh: true, - body: { - query: { - ids: { values: docIds }, - }, + query: { + ids: { values: docIds }, }, }); }; diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/remote_clusters.ts b/x-pack/test/api_integration/apis/upgrade_assistant/remote_clusters.ts index d8daee96e80b8..54b017dc99fb3 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/remote_clusters.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/remote_clusters.ts @@ -21,13 +21,11 @@ export default function ({ getService }: FtrProviderContext) { try { // Configure a remote cluster await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - remote: { - test_cluster: { - seeds: ['127.0.0.1:9400'], - }, + persistent: { + cluster: { + remote: { + test_cluster: { + seeds: ['127.0.0.1:9400'], }, }, }, @@ -43,13 +41,11 @@ export default function ({ getService }: FtrProviderContext) { try { // Delete remote cluster await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - remote: { - test_cluster: { - seeds: null, - }, + persistent: { + cluster: { + remote: { + test_cluster: { + seeds: null, }, }, }, diff --git a/x-pack/test/api_integration/apis/uptime/rest/helper/make_ping.ts b/x-pack/test/api_integration/apis/uptime/rest/helper/make_ping.ts index d7259f85c60eb..009f9a69cd31f 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/helper/make_ping.ts +++ b/x-pack/test/api_integration/apis/uptime/rest/helper/make_ping.ts @@ -114,13 +114,13 @@ export const makePing = async ( baseDoc.tls = makeTls(tls as any); } - const doc = mogrify(merge(baseDoc, fields)); + const document = mogrify(merge(baseDoc, fields)); await es.index({ index: customIndex || DEFAULT_INDEX_NAME, refresh, - body: doc, + document, }); - return doc; + return document; }; diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_add_semantic_text_field_migration.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_add_semantic_text_field_migration.spec.ts index 3390cd3ef35c4..51f74ccc0716d 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_add_semantic_text_field_migration.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_add_semantic_text_field_migration.spec.ts @@ -8,7 +8,7 @@ import { orderBy } from 'lodash'; import expect from '@kbn/expect'; import { AI_ASSISTANT_KB_INFERENCE_ID } from '@kbn/observability-ai-assistant-plugin/server/service/inference_endpoint'; -import { SearchResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { KnowledgeBaseEntry } from '@kbn/observability-ai-assistant-plugin/common'; import type { DeploymentAgnosticFtrProviderContext } from '../../../../ftr_provider_context'; import { @@ -57,10 +57,8 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon index: '.kibana-observability-ai-assistant-kb*', // Add fields parameter to include inference metadata fields: ['_inference_fields'], - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, })) as SearchResponse; diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_reindex.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_reindex.spec.ts index 79c6b963a852e..0b2a335e69d75 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_reindex.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/ai_assistant/knowledge_base/knowledge_base_reindex.spec.ts @@ -130,9 +130,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon repository: snapshotRepoName, snapshot: snapshotName, wait_for_completion: true, - body: { - indices: resourceNames.concreteIndexName.kb, - }, + indices: resourceNames.concreteIndexName.kb, }); await es.snapshot.deleteRepository({ name: snapshotRepoName }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/diagnostics/indices.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/diagnostics/indices.spec.ts index af0249d2a3359..747630329935a 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/diagnostics/indices.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/diagnostics/indices.spec.ts @@ -147,7 +147,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon await es.indices.putSettings({ index: datastreamToUpdate.data_streams[0].indices[0].index_name, // @ts-expect-error: Allow null values in https://github.com/elastic/elasticsearch-specification/pull/2126 - body: { index: { default_pipeline: null } }, + settings: { index: { default_pipeline: null } }, }); }); @@ -176,7 +176,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon }); await es.indices.putSettings({ index: datastreamToUpdate.data_streams[0].indices[0].index_name, - body: { index: { default_pipeline: 'logs-default-pipeline' } }, + settings: { index: { default_pipeline: 'logs-default-pipeline' } }, }); }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_groups/service_group_with_overflow/service_group_with_overflow.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_groups/service_group_with_overflow/service_group_with_overflow.spec.ts index b5cbf1ae2566c..4a7ca49d3e1fe 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_groups/service_group_with_overflow/service_group_with_overflow.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_groups/service_group_with_overflow/service_group_with_overflow.spec.ts @@ -49,7 +49,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon }), ]; - const bulkActions = docs.reduce( + const operations = docs.reduce( (prev, doc) => { return [...prev, { create: { _index: indexName } }, doc]; }, @@ -64,7 +64,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon ); await es.bulk({ - body: bulkActions, + operations, refresh: 'wait_for', }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/es_utils.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/es_utils.ts index 453f7a50d8aa3..7d49cd7217a24 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/es_utils.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/es_utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { v4 as uuidv4 } from 'uuid'; export function createServiceDependencyDocs({ diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/index.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/index.spec.ts index a579e196e7aa4..29f7aaa7e0d08 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/index.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/service_overview/dependencies/index.spec.ts @@ -87,23 +87,17 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon before(async () => { await es.indices.create({ index: indices.metric, - body: { - mappings: apmDependenciesMapping, - }, + mappings: apmDependenciesMapping, }); await es.indices.create({ index: indices.transaction, - body: { - mappings: apmDependenciesMapping, - }, + mappings: apmDependenciesMapping, }); await es.indices.create({ index: indices.span, - body: { - mappings: apmDependenciesMapping, - }, + mappings: apmDependenciesMapping, }); const docs = [ @@ -193,7 +187,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon }), ]; - const bulkActions = docs.reduce( + const operations = docs.reduce( (prev, doc) => { return [...prev, { index: { _index: indices[doc.processor.event] } }, doc]; }, @@ -208,7 +202,7 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon ); await es.bulk({ - body: bulkActions, + operations, refresh: 'wait_for', }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/services/derived_annotations.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/services/derived_annotations.spec.ts index 272ddb876573f..ecd73fb048949 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/services/derived_annotations.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/services/derived_annotations.spec.ts @@ -41,37 +41,35 @@ export default function annotationApiTests({ getService }: DeploymentAgnosticFtr await es.indices.create({ index: indexName, - body: { - mappings: { - properties: { - service: { - properties: { - name: { - type: 'keyword', - }, - version: { - type: 'keyword', - }, - environment: { - type: 'keyword', - }, + mappings: { + properties: { + service: { + properties: { + name: { + type: 'keyword', + }, + version: { + type: 'keyword', + }, + environment: { + type: 'keyword', }, }, - transaction: { - properties: { - type: { - type: 'keyword', - }, - duration: { - type: 'long', - }, + }, + transaction: { + properties: { + type: { + type: 'keyword', + }, + duration: { + type: 'long', }, }, - processor: { - properties: { - event: { - type: 'keyword', - }, + }, + processor: { + properties: { + event: { + type: 'keyword', }, }, }, @@ -113,7 +111,7 @@ export default function annotationApiTests({ getService }: DeploymentAgnosticFtr await es.bulk({ index: indexName, - body: docs.flatMap((doc) => [{ index: {} }, doc]), + operations: docs.flatMap((doc) => [{ index: {} }, doc]), refresh: true, }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/time_range_metadata/many_apm_server_versions.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/time_range_metadata/many_apm_server_versions.spec.ts index 31012e6dd6d63..261cc03049908 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/time_range_metadata/many_apm_server_versions.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/time_range_metadata/many_apm_server_versions.spec.ts @@ -60,14 +60,12 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon it('ingests transaction metrics with transaction.duration.summary', async () => { const res = await es.search({ index: 'metrics-apm*', - body: { - query: { - bool: { - filter: [ - { exists: { field: TRANSACTION_DURATION_HISTOGRAM } }, - { exists: { field: TRANSACTION_DURATION_SUMMARY } }, - ], - }, + query: { + bool: { + filter: [ + { exists: { field: TRANSACTION_DURATION_HISTOGRAM } }, + { exists: { field: TRANSACTION_DURATION_SUMMARY } }, + ], }, }, }); @@ -79,12 +77,10 @@ export default function ApiTest({ getService }: DeploymentAgnosticFtrProviderCon it('ingests transaction metrics without transaction.duration.summary', async () => { const res = await es.search({ index: 'metrics-apm*', - body: { - query: { - bool: { - filter: [{ exists: { field: TRANSACTION_DURATION_HISTOGRAM } }], - must_not: [{ exists: { field: TRANSACTION_DURATION_SUMMARY } }], - }, + query: { + bool: { + filter: [{ exists: { field: TRANSACTION_DURATION_HISTOGRAM } }], + must_not: [{ exists: { field: TRANSACTION_DURATION_SUMMARY } }], }, }, }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/traces/large_trace/large_trace.spec.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/traces/large_trace/large_trace.spec.ts index 7a0952b856c6b..c08e6716d1fed 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/traces/large_trace/large_trace.spec.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/apm/traces/large_trace/large_trace.spec.ts @@ -102,15 +102,13 @@ async function getRootTransaction(es: Client) { const params = { index: 'traces-apm*', _source: [TRACE_ID, TRANSACTION_ID], - body: { - query: { - bool: { - filter: [ - { term: { [PROCESSOR_EVENT]: 'transaction' } }, - { term: { [SERVICE_ENVIRONMENT]: environment } }, - ], - must_not: [{ exists: { field: PARENT_ID } }], - }, + query: { + bool: { + filter: [ + { term: { [PROCESSOR_EVENT]: 'transaction' } }, + { term: { [SERVICE_ENVIRONMENT]: environment } }, + ], + must_not: [{ exists: { field: PARENT_ID } }], }, }, }; diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/create_slo.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/create_slo.ts index d5100075b5eca..3e74f02d504db 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/create_slo.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/create_slo.ts @@ -235,7 +235,7 @@ const getRollupDataEsQuery = (id: string) => ({ sort: [ { '@timestamp': { - order: 'desc', + order: 'desc' as const, }, }, ], diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/delete_slo.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/delete_slo.ts index d1e3fe6e53b68..c927418ad6496 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/delete_slo.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/delete_slo.ts @@ -74,18 +74,16 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { await retry.waitForWithTimeout('SLO summary data is deleted', 60 * 1000, async () => { const sloSummaryResponseAfterDeletion = await esClient.search({ index: SUMMARY_DESTINATION_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - { - term: { 'slo.id': id }, - }, - { - term: { isTempDoc: false }, - }, - ], - }, + query: { + bool: { + filter: [ + { + term: { 'slo.id': id }, + }, + { + term: { isTempDoc: false }, + }, + ], }, }, }); @@ -98,15 +96,13 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { await retry.waitForWithTimeout('SLO rollup data is deleted', 60 * 1000, async () => { const sloRollupResponseAfterDeletion = await esClient.search({ index: SLI_DESTINATION_INDEX_PATTERN, - body: { - query: { - bool: { - filter: [ - { - term: { 'slo.id': id }, - }, - ], - }, + query: { + bool: { + filter: [ + { + term: { 'slo.id': id }, + }, + ], }, }, }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/classic.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/classic.ts index 6269e5b19347d..4b4b14aeb368d 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/classic.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/classic.ts @@ -250,19 +250,17 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { before(async () => { await esClient.indices.putIndexTemplate({ name: TEMPLATE_NAME, - body: { - index_patterns: ['mytest*'], - priority: 1000, - template: { - lifecycle: { - data_retention: '7d', - }, - }, - data_stream: { - allow_custom_routing: false, - hidden: false, + index_patterns: ['mytest*'], + priority: 1000, + template: { + lifecycle: { + data_retention: '7d', }, }, + data_stream: { + allow_custom_routing: false, + hidden: false, + }, }); await esClient.indices.createDataStream({ diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/enrichment.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/enrichment.ts index 1fc0412a0f76a..7be4d4851510a 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/enrichment.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/enrichment.ts @@ -151,11 +151,9 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { it('Doc is searchable', async () => { const response = await esClient.search({ index: 'logs.nginx', - body: { - query: { - match: { - message2: 'mylogger', - }, + query: { + match: { + message2: 'mylogger', }, }, }); @@ -165,11 +163,9 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { it('Non-indexed field is not searchable', async () => { const response = await esClient.search({ index: 'logs.nginx', - body: { - query: { - match: { - 'log.logger': 'mylogger', - }, + query: { + match: { + 'log.logger': 'mylogger', }, }, }); diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/helpers/requests.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/helpers/requests.ts index b5fafd40036a1..2ca2cd306ce72 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/helpers/requests.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/streams/helpers/requests.ts @@ -7,7 +7,7 @@ import { Client } from '@elastic/elasticsearch'; import { JsonObject } from '@kbn/utility-types'; import expect from '@kbn/expect'; -import { SearchTotalHits } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SearchTotalHits } from '@elastic/elasticsearch/lib/api/types'; import { StreamUpsertRequest } from '@kbn/streams-schema'; import { ClientRequestParamsOf } from '@kbn/server-route-repository-utils'; import { StreamsRouteRepository } from '@kbn/streams-plugin/server'; diff --git a/x-pack/test/api_integration/deployment_agnostic/services/alerting_api.ts b/x-pack/test/api_integration/deployment_agnostic/services/alerting_api.ts index f75f5d297c740..ce7a6e6ce8eef 100644 --- a/x-pack/test/api_integration/deployment_agnostic/services/alerting_api.ts +++ b/x-pack/test/api_integration/deployment_agnostic/services/alerting_api.ts @@ -97,24 +97,22 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide async () => { const response = await esClient.search({ index: indexName, - body: { - query: { - bool: { - must: [ - { - term: { - 'kibana.alert.rule.uuid': ruleId, - }, + query: { + bool: { + must: [ + { + term: { + 'kibana.alert.rule.uuid': ruleId, }, - { - range: { - '@timestamp': { - gte: filter.getTime().toString(), - }, + }, + { + range: { + '@timestamp': { + gte: filter.getTime().toString(), }, }, - ], - }, + }, + ], }, }, }); @@ -146,17 +144,15 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide const response = await esClient.search({ index: indexName, sort: `date:${sort}`, - body: { - query: { - bool: { - must: [ - { - term: { - 'ruleId.keyword': ruleId, - }, + query: { + bool: { + must: [ + { + term: { + 'ruleId.keyword': ruleId, }, - ], - }, + }, + ], }, }, }); @@ -188,17 +184,15 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide const response = await esClient.search({ index: indexName, sort: `date:${sort}`, - body: { - query: { - bool: { - must: [ - { - term: { - 'ruleId.keyword': ruleId, - }, + query: { + bool: { + must: [ + { + term: { + 'ruleId.keyword': ruleId, }, - ], - }, + }, + ], }, }, }); @@ -635,17 +629,15 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide const response = await esClient.search({ index: indexName, sort: `date:${sort}`, - body: { - query: { - bool: { - must: [ - { - term: { - 'ruleId.keyword': ruleId, - }, + query: { + bool: { + must: [ + { + term: { + 'ruleId.keyword': ruleId, }, - ], - }, + }, + ], }, }, }); @@ -669,17 +661,15 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide }): Promise { return await esClient.search({ index: indexName, - body: { - query: { - bool: { - must: [ - { - term: { - 'ruleId.keyword': ruleId, - }, + query: { + bool: { + must: [ + { + term: { + 'ruleId.keyword': ruleId, }, - ], - }, + }, + ], }, }, }); @@ -701,31 +691,29 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide async () => { const response = await esClient.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - terms: { - 'task.scope': ['actions', 'alerting'], - }, + query: { + bool: { + must: [ + { + terms: { + 'task.scope': ['actions', 'alerting'], }, - { - range: { - 'task.scheduledAt': { - gte: filter.getTime().toString(), - }, + }, + { + range: { + 'task.scheduledAt': { + gte: filter.getTime().toString(), }, }, - ], - must_not: [ - { - term: { - 'task.status': 'idle', - }, + }, + ], + must_not: [ + { + term: { + 'task.status': 'idle', }, - ], - }, + }, + ], }, }, }); @@ -758,38 +746,36 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide async () => { const response = await esClient.search({ index: '.kibana-event-log*', - body: { - query: { - bool: { - filter: [ - { - term: { - 'rule.id': { - value: ruleId, - }, + query: { + bool: { + filter: [ + { + term: { + 'rule.id': { + value: ruleId, }, }, - { - term: { - 'event.provider': { - value: 'alerting', - }, + }, + { + term: { + 'event.provider': { + value: 'alerting', }, }, - { - term: { - 'event.action': 'execute', - }, + }, + { + term: { + 'event.action': 'execute', }, - { - range: { - '@timestamp': { - gte: filter.getTime().toString(), - }, + }, + { + range: { + '@timestamp': { + gte: filter.getTime().toString(), }, }, - ], - }, + }, + ], }, }, }); @@ -806,7 +792,6 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide return await esClient.indices.create( { index: indexName, - body: {}, }, { meta: true } ); @@ -830,39 +815,37 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide async () => { const response = await esClient.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.status': 'idle', - }, + query: { + bool: { + must: [ + { + term: { + 'task.status': 'idle', }, - { - term: { - 'task.attempts': attempts, - }, + }, + { + term: { + 'task.attempts': attempts, }, - { - terms: { - 'task.scope': ['actions', 'alerting'], - }, + }, + { + terms: { + 'task.scope': ['actions', 'alerting'], }, - { - term: { - 'task.taskType': taskType, - }, + }, + { + term: { + 'task.taskType': taskType, }, - { - range: { - 'task.scheduledAt': { - gte: filter.getTime().toString(), - }, + }, + { + range: { + 'task.scheduledAt': { + gte: filter.getTime().toString(), }, }, - ], - }, + }, + ], }, }, }); @@ -891,34 +874,32 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide async () => { const response = await esClient.search({ index: '.kibana_task_manager', - body: { - query: { - bool: { - must: [ - { - term: { - 'task.id': `task:${ruleId}`, - }, + query: { + bool: { + must: [ + { + term: { + 'task.id': `task:${ruleId}`, }, - { - terms: { - 'task.scope': ['actions', 'alerting'], - }, + }, + { + terms: { + 'task.scope': ['actions', 'alerting'], }, - { - range: { - 'task.scheduledAt': { - gte: filter.getTime().toString(), - }, + }, + { + range: { + 'task.scheduledAt': { + gte: filter.getTime().toString(), }, }, - { - term: { - 'task.enabled': true, - }, + }, + { + term: { + 'task.enabled': true, }, - ], - }, + }, + ], }, }, }); @@ -976,11 +957,9 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide rest_total_hits_as_int: true, ...(ruleId ? { - body: { - query: { - term: { - 'kibana.alert.rule.uuid': ruleId, - }, + query: { + term: { + 'kibana.alert.rule.uuid': ruleId, }, }, } @@ -1014,11 +993,9 @@ export function AlertingApiProvider({ getService }: DeploymentAgnosticFtrProvide return await retry.tryForTime(retryTimeout, async () => { const response = await es.search({ index: indexName, - body: { - query: { - term: { - 'kibana.alert.rule.uuid': ruleId, - }, + query: { + term: { + 'kibana.alert.rule.uuid': ruleId, }, }, }); diff --git a/x-pack/test/apm_api_integration/tests/alerts/helpers/wait_for_alerts_for_rule.ts b/x-pack/test/apm_api_integration/tests/alerts/helpers/wait_for_alerts_for_rule.ts index 6df58b50baa24..b7b219da56a75 100644 --- a/x-pack/test/apm_api_integration/tests/alerts/helpers/wait_for_alerts_for_rule.ts +++ b/x-pack/test/apm_api_integration/tests/alerts/helpers/wait_for_alerts_for_rule.ts @@ -6,10 +6,7 @@ */ import type { Client } from '@elastic/elasticsearch'; -import type { - AggregationsAggregate, - SearchResponse, -} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { AggregationsAggregate, SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { ToolingLog } from '@kbn/tooling-log'; import { retryForSuccess } from '@kbn/ftr-common-functional-services'; import { @@ -22,11 +19,9 @@ const debugLog = ToolingLog.bind(ToolingLog, { level: 'debug', writeTo: process. async function getAlertByRuleId({ es, ruleId }: { es: Client; ruleId: string }) { const response = (await es.search({ index: APM_ALERTS_INDEX, - body: { - query: { - term: { - 'kibana.alert.rule.uuid': ruleId, - }, + query: { + term: { + 'kibana.alert.rule.uuid': ruleId, }, }, })) as SearchResponse>; diff --git a/x-pack/test/apm_api_integration/tests/event_metadata/event_metadata.spec.ts b/x-pack/test/apm_api_integration/tests/event_metadata/event_metadata.spec.ts index f89447f5f2b92..c9dc15903e517 100644 --- a/x-pack/test/apm_api_integration/tests/event_metadata/event_metadata.spec.ts +++ b/x-pack/test/apm_api_integration/tests/event_metadata/event_metadata.spec.ts @@ -20,17 +20,15 @@ export default function ApiTest({ getService }: FtrProviderContext) { async function getMostRecentDoc(processorEvent: ProcessorEvent) { const response = await es.search({ index: ['apm-*'], - body: { - query: { - bool: { - filter: [{ term: { [PROCESSOR_EVENT]: processorEvent } }], - }, - }, - size: 1, - sort: { - '@timestamp': 'desc', + query: { + bool: { + filter: [{ term: { [PROCESSOR_EVENT]: processorEvent } }], }, }, + size: 1, + sort: { + '@timestamp': 'desc', + }, }); const doc = response.hits.hits[0]._source!; diff --git a/x-pack/test/apm_api_integration/tests/fleet/input_only_package.spec.ts b/x-pack/test/apm_api_integration/tests/fleet/input_only_package.spec.ts index 3aea453050541..013ffa213d353 100644 --- a/x-pack/test/apm_api_integration/tests/fleet/input_only_package.spec.ts +++ b/x-pack/test/apm_api_integration/tests/fleet/input_only_package.spec.ts @@ -11,7 +11,7 @@ import expect from '@kbn/expect'; import { createEsClientForFtrConfig } from '@kbn/test'; import { ApmDocumentType } from '@kbn/apm-plugin/common/document_type'; import { RollupInterval } from '@kbn/apm-plugin/common/rollup'; -import { SecurityRoleDescriptor } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { SecurityRoleDescriptor } from '@elastic/elasticsearch/lib/api/types'; import { RetryService } from '@kbn/ftr-common-functional-services'; import { FtrProviderContext } from '../../common/ftr_provider_context'; import { getBettertest } from '../../common/bettertest'; @@ -59,11 +59,9 @@ export default function ApiTest(ftrProviderContext: FtrProviderContext) { const esClientScoped = createEsClientWithToken(token.value); return esClientScoped.security.createApiKey({ - body: { - name: API_KEY_NAME, - role_descriptors: { - apmFleetPermissions: permissions, - }, + name: API_KEY_NAME, + role_descriptors: { + apmFleetPermissions: permissions, }, }); } diff --git a/x-pack/test/apm_api_integration/tests/services/annotations.spec.ts b/x-pack/test/apm_api_integration/tests/services/annotations.spec.ts index f34a8c6cea2fb..d03e01dfea484 100644 --- a/x-pack/test/apm_api_integration/tests/services/annotations.spec.ts +++ b/x-pack/test/apm_api_integration/tests/services/annotations.spec.ts @@ -211,25 +211,23 @@ export default function annotationApiTests({ getService }: FtrProviderContext) { beforeEach(async () => { await es.indices.create({ index: transactionIndexName, - body: { - mappings: { - properties: { - service: { - properties: { - name: { - type: 'keyword', - }, - version: { - type: 'keyword', - }, - environment: { - type: 'keyword', - }, + mappings: { + properties: { + service: { + properties: { + name: { + type: 'keyword', + }, + version: { + type: 'keyword', + }, + environment: { + type: 'keyword', }, }, - '@timestamp': { - type: 'date', - }, + }, + '@timestamp': { + type: 'date', }, }, }, @@ -237,7 +235,7 @@ export default function annotationApiTests({ getService }: FtrProviderContext) { await es.index({ index: transactionIndexName, - body: { + document: { '@timestamp': new Date(2020, 4, 2, 18, 30).toISOString(), processor: { event: 'transaction', @@ -252,7 +250,7 @@ export default function annotationApiTests({ getService }: FtrProviderContext) { await es.index({ index: transactionIndexName, - body: { + document: { '@timestamp': new Date(2020, 4, 2, 19, 30).toISOString(), processor: { event: 'transaction', diff --git a/x-pack/test/cases_api_integration/common/lib/alerts.ts b/x-pack/test/cases_api_integration/common/lib/alerts.ts index 8df074b0d3474..231bae0ea28fe 100644 --- a/x-pack/test/cases_api_integration/common/lib/alerts.ts +++ b/x-pack/test/cases_api_integration/common/lib/alerts.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import type SuperTest from 'supertest'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ToolingLog } from '@kbn/tooling-log'; import { DETECTION_ENGINE_QUERY_SIGNALS_URL } from '@kbn/security-solution-plugin/common/constants'; import { DetectionAlert } from '@kbn/security-solution-plugin/common/api/detection_engine'; diff --git a/x-pack/test/cases_api_integration/common/lib/api/index.ts b/x-pack/test/cases_api_integration/common/lib/api/index.ts index e59a248ec42ce..05979b8960a34 100644 --- a/x-pack/test/cases_api_integration/common/lib/api/index.ts +++ b/x-pack/test/cases_api_integration/common/lib/api/index.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportResult } from '@elastic/elasticsearch'; import type { Client } from '@elastic/elasticsearch'; import { GetResponse } from '@elastic/elasticsearch/lib/api/types'; @@ -99,18 +99,16 @@ export const getSignalsWithES = async ({ const signals: TransportResult, unknown> = await es.search( { index: indices, - body: { - size: 10000, - query: { - bool: { - filter: [ - { - ids: { - values: toArray(ids), - }, + size: 10000, + query: { + bool: { + filter: [ + { + ids: { + values: toArray(ids), }, - ], - }, + }, + ], }, }, }, @@ -306,12 +304,10 @@ export const getConnectorMappingsFromES = async ({ es }: { es: Client }) => { > = await es.search( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - type: { - value: 'cases-connector-mappings', - }, + query: { + term: { + type: { + value: 'cases-connector-mappings', }, }, }, @@ -336,12 +332,10 @@ export const getConfigureSavedObjectsFromES = async ({ es }: { es: Client }) => > = await es.search( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - type: { - value: CASE_CONFIGURE_SAVED_OBJECT, - }, + query: { + term: { + type: { + value: CASE_CONFIGURE_SAVED_OBJECT, }, }, }, @@ -359,12 +353,10 @@ export const getCaseSavedObjectsFromES = async ({ es }: { es: Client }) => { > = await es.search( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - type: { - value: CASE_SAVED_OBJECT, - }, + query: { + term: { + type: { + value: CASE_SAVED_OBJECT, }, }, }, @@ -382,12 +374,10 @@ export const getCaseCommentSavedObjectsFromES = async ({ es }: { es: Client }) = > = await es.search( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - type: { - value: CASE_COMMENT_SAVED_OBJECT, - }, + query: { + term: { + type: { + value: CASE_COMMENT_SAVED_OBJECT, }, }, }, @@ -405,12 +395,10 @@ export const getCaseUserActionsSavedObjectsFromES = async ({ es }: { es: Client > = await es.search( { index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - query: { - term: { - type: { - value: CASE_USER_ACTION_SAVED_OBJECT, - }, + query: { + term: { + type: { + value: CASE_USER_ACTION_SAVED_OBJECT, }, }, }, diff --git a/x-pack/test/cases_api_integration/security_and_spaces/tests/common/cases/find_cases.ts b/x-pack/test/cases_api_integration/security_and_spaces/tests/common/cases/find_cases.ts index ccfae3068f5dc..87f2a4f2acb39 100644 --- a/x-pack/test/cases_api_integration/security_and_spaces/tests/common/cases/find_cases.ts +++ b/x-pack/test/cases_api_integration/security_and_spaces/tests/common/cases/find_cases.ts @@ -645,12 +645,10 @@ export default ({ getService }: FtrProviderContext): void => { const getAllCasesSortedByCreatedAtAsc = async () => { const cases = await es.search({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - size: 10000, - sort: [{ 'cases.created_at': { unmapped_type: 'date', order: 'asc' } }], - query: { - term: { type: 'cases' }, - }, + size: 10000, + sort: [{ 'cases.created_at': { unmapped_type: 'date', order: 'asc' } }], + query: { + term: { type: 'cases' }, }, }); return cases.hits.hits.map((hit) => hit._source); diff --git a/x-pack/test/cloud_security_posture_functional/page_objects/csp_dashboard_page.ts b/x-pack/test/cloud_security_posture_functional/page_objects/csp_dashboard_page.ts index 8827437a19332..26755763287ff 100644 --- a/x-pack/test/cloud_security_posture_functional/page_objects/csp_dashboard_page.ts +++ b/x-pack/test/cloud_security_posture_functional/page_objects/csp_dashboard_page.ts @@ -45,7 +45,7 @@ export function CspDashboardPageProvider({ getService, getPageObjects }: FtrProv findingsMock.map((finding) => es.index({ index: LATEST_FINDINGS_INDEX, - body: finding, + document: finding, }) ) ); diff --git a/x-pack/test/cloud_security_posture_functional/page_objects/vulnerability_dashboard_page_object.ts b/x-pack/test/cloud_security_posture_functional/page_objects/vulnerability_dashboard_page_object.ts index a53dd82f841d5..6489285033acd 100644 --- a/x-pack/test/cloud_security_posture_functional/page_objects/vulnerability_dashboard_page_object.ts +++ b/x-pack/test/cloud_security_posture_functional/page_objects/vulnerability_dashboard_page_object.ts @@ -60,7 +60,7 @@ export function VulnerabilityDashboardPageProvider({ vulnerabilitiesMock.map((vulnerabilityDoc) => es.index({ index: VULNERABILITIES_LATEST_INDEX, - body: vulnerabilityDoc, + document: vulnerabilityDoc, refresh: true, }) ) @@ -72,7 +72,7 @@ export function VulnerabilityDashboardPageProvider({ scoresMock.map((scoreDoc) => es.index({ index: BENCHMARK_SCORES_INDEX, - body: scoreDoc, + document: scoreDoc, refresh: true, }) ) diff --git a/x-pack/test/common/lib/test_data_loader.ts b/x-pack/test/common/lib/test_data_loader.ts index d8f7453c89ddb..a31bf96812f22 100644 --- a/x-pack/test/common/lib/test_data_loader.ts +++ b/x-pack/test/common/lib/test_data_loader.ts @@ -179,21 +179,18 @@ export function getTestDataLoader({ getService }: Pick { await es.deleteByQuery({ index, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, refresh: true, }); diff --git a/x-pack/test/common/utils/security_solution/detections_response/tasks/indices_metadata.ts b/x-pack/test/common/utils/security_solution/detections_response/tasks/indices_metadata.ts index 0c4d90749e423..d2888b486f034 100644 --- a/x-pack/test/common/utils/security_solution/detections_response/tasks/indices_metadata.ts +++ b/x-pack/test/common/utils/security_solution/detections_response/tasks/indices_metadata.ts @@ -32,7 +32,7 @@ export const randomDatastream = async (es: Client, policyName?: string): Promise await es.indices.putIndexTemplate({ name: DS_PREFIX, - body: indexTemplateBody, + ...indexTemplateBody, }); await es.indices.createDataStream({ name }); diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/es_utils.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/es_utils.ts index 5217c887a93ff..6c32e51e51968 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/es_utils.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/es_utils.ts @@ -30,6 +30,11 @@ export async function addIntegrationToLogIndexTemplate({ }, managed_by: managedBy, }, + // PUT expects string[] while GET might return string | string[] + ignore_missing_component_templates: indexTemplates[0].index_template + .ignore_missing_component_templates + ? [indexTemplates[0].index_template.ignore_missing_component_templates].flat() + : undefined, }); } @@ -46,5 +51,10 @@ export async function cleanLogIndexTemplate({ esClient }: { esClient: Client }) package: undefined, managed_by: undefined, }, + // PUT expects string[] while GET might return string | string[] + ignore_missing_component_templates: indexTemplates[0].index_template + .ignore_missing_component_templates + ? [indexTemplates[0].index_template.ignore_missing_component_templates].flat() + : undefined, }); } diff --git a/x-pack/test/fleet_api_integration/apis/agent_policy/agent_policy_with_agents_setup.ts b/x-pack/test/fleet_api_integration/apis/agent_policy/agent_policy_with_agents_setup.ts index f9c83c3fc3146..53c5d87b24b03 100644 --- a/x-pack/test/fleet_api_integration/apis/agent_policy/agent_policy_with_agents_setup.ts +++ b/x-pack/test/fleet_api_integration/apis/agent_policy/agent_policy_with_agents_setup.ts @@ -40,15 +40,13 @@ export default function (providerContext: FtrProviderContext) { const res = await esClient.search({ index: AGENT_POLICY_INDEX, ignore_unavailable: true, - body: { - query: { - term: { - policy_id: policyId, - }, + query: { + term: { + policy_id: policyId, }, - size: 1, - sort: [{ revision_idx: { order: 'desc' } }], }, + size: 1, + sort: [{ revision_idx: { order: 'desc' } }], }); if (spaceId) { @@ -64,14 +62,12 @@ export default function (providerContext: FtrProviderContext) { const res = await esClient.search({ index: ENROLLMENT_API_KEYS_INDEX, ignore_unavailable: true, - body: { - query: { - term: { - policy_id: policyId, - }, + query: { + term: { + policy_id: policyId, }, - size: 1, }, + size: 1, }); if (spaceId) { diff --git a/x-pack/test/fleet_api_integration/apis/agents/actions.ts b/x-pack/test/fleet_api_integration/apis/agents/actions.ts index 57b367f8c4bd0..4b2279daf3cbb 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/actions.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/actions.ts @@ -132,7 +132,7 @@ export default function (providerContext: FtrProviderContext) { index: '.fleet-actions', refresh: 'wait_for', id: uuidv4(), - body: { + document: { '@timestamp': new Date().toISOString(), expiration: new Date().toISOString(), agents: ['agent1', 'agent2'], @@ -148,9 +148,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' as const } }], }); const action: any = actionsRes.hits.hits[0]._source; diff --git a/x-pack/test/fleet_api_integration/apis/agents/list.ts b/x-pack/test/fleet_api_integration/apis/agents/list.ts index 505a703604801..dc63eaac8d46c 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/list.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/list.ts @@ -222,13 +222,11 @@ export default function ({ getService }: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_revision_idx: 1, - last_checkin: new Date().toISOString(), - status: 'online', - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + policy_revision_idx: 1, + last_checkin: new Date().toISOString(), + status: 'online', + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); // 1 agent inactive @@ -236,14 +234,12 @@ export default function ({ getService }: FtrProviderContext) { id: 'agent4', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: 'policy-inactivity-timeout', - policy_revision_idx: 1, - last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min - status: 'online', - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + policy_id: 'policy-inactivity-timeout', + policy_revision_idx: 1, + last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min + status: 'online', + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); diff --git a/x-pack/test/fleet_api_integration/apis/agents/privileges.ts b/x-pack/test/fleet_api_integration/apis/agents/privileges.ts index 0b503e28cf136..c9783bda70b4e 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/privileges.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/privileges.ts @@ -216,7 +216,7 @@ export default function (providerContext: FtrProviderContext) { id: 'file1', refresh: true, op_type: 'create', - body: { + document: { '@timestamp': new Date().toISOString(), upload_id: 'file1', action_id: `fleet_uploads_test-file1-action`, diff --git a/x-pack/test/fleet_api_integration/apis/agents/request_diagnostics.ts b/x-pack/test/fleet_api_integration/apis/agents/request_diagnostics.ts index b8d1dda4a9ebe..a24ded48ec3f0 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/request_diagnostics.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/request_diagnostics.ts @@ -138,9 +138,7 @@ export default function (providerContext: FtrProviderContext) { .expect(200); const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; expect(action.data.additional_metrics).contain('CPU'); @@ -158,9 +156,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; expect(action.data.additional_metrics).contain('CPU'); diff --git a/x-pack/test/fleet_api_integration/apis/agents/status.ts b/x-pack/test/fleet_api_integration/apis/agents/status.ts index 9805ca84b9718..78261ad959c16 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/status.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/status.ts @@ -48,22 +48,18 @@ export default function ({ getService }: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_revision_idx: 1, - last_checkin: new Date().toISOString(), - }, + doc: { + policy_revision_idx: 1, + last_checkin: new Date().toISOString(), }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_revision_idx: 1, - last_checkin: new Date(Date.now() - 1000 * 60 * 3).toISOString(), // 2m online - }, + doc: { + policy_revision_idx: 1, + last_checkin: new Date(Date.now() - 1000 * 60 * 3).toISOString(), // 2m online }, }); // 1 agents offline @@ -71,11 +67,9 @@ export default function ({ getService }: FtrProviderContext) { id: 'agent3', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_revision_idx: 1, - last_checkin: new Date(Date.now() - 1000 * 60 * 6).toISOString(), // 6m offline - }, + doc: { + policy_revision_idx: 1, + last_checkin: new Date(Date.now() - 1000 * 60 * 6).toISOString(), // 6m offline }, }); // 1 agents inactive @@ -83,12 +77,10 @@ export default function ({ getService }: FtrProviderContext) { id: 'agent4', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: 'policy-inactivity-timeout', - policy_revision_idx: 1, - last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min - }, + doc: { + policy_id: 'policy-inactivity-timeout', + policy_revision_idx: 1, + last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min }, }); // 1 agents inactive through enrolled_at as no last_checkin diff --git a/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts b/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts index 66744fd9181cd..d09ad9bb08439 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/unenroll.ts @@ -32,15 +32,11 @@ export default function (providerContext: FtrProviderContext) { await esArchiver.load('x-pack/test/functional/es_archives/fleet/agents'); await getService('supertest').post(`/api/fleet/setup`).set('kbn-xsrf', 'xxx').send(); const accessAPIKeyBody = await esClient.security.createApiKey({ - body: { - name: `test access api key: ${uuidv4()}`, - }, + name: `test access api key: ${uuidv4()}`, }); accessAPIKeyId = accessAPIKeyBody.id; const outputAPIKeyBody = await esClient.security.createApiKey({ - body: { - name: `test output api key: ${uuidv4()}`, - }, + name: `test output api key: ${uuidv4()}`, }); outputAPIKeyId = outputAPIKeyBody.id; const { _source: agentDoc } = await esClient.get({ @@ -60,9 +56,7 @@ export default function (providerContext: FtrProviderContext) { index: '.fleet-agents', id: 'agent1', refresh: true, - body: { - doc: agentDoc, - }, + doc: agentDoc, }); }); afterEach(async () => { @@ -195,12 +189,10 @@ export default function (providerContext: FtrProviderContext) { id: 'agent4', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: 'policy1', - policy_revision_idx: 1, - last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min - }, + doc: { + policy_id: 'policy1', + policy_revision_idx: 1, + last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min }, }); // unenroll all agents that had last checkin before "now" @@ -223,12 +215,10 @@ export default function (providerContext: FtrProviderContext) { id: 'agent4', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: 'policy1', - policy_revision_idx: 1, - last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min - }, + doc: { + policy_id: 'policy1', + policy_revision_idx: 1, + last_checkin: new Date(Date.now() - 1000 * 60).toISOString(), // policy timeout 1 min }, }); // agent inactive through enrolled_at as no last_checkin diff --git a/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts b/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts index e316731602fea..2019d4fa1e466 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/upgrade.ts @@ -95,10 +95,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -133,11 +131,9 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { agent: { upgradeable: true, version: fleetServerVersion } }, - }, + doc: { + local_metadata: { + elastic: { agent: { upgradeable: true, version: fleetServerVersion } }, }, }, }); @@ -159,11 +155,9 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { agent: { upgradeable: true, version: fleetServerVersion } }, - }, + doc: { + local_metadata: { + elastic: { agent: { upgradeable: true, version: fleetServerVersion } }, }, }, }); @@ -184,10 +178,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -204,10 +196,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -220,9 +210,7 @@ export default function (providerContext: FtrProviderContext) { .expect(200); const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; expect(action.data.sourceURI).contain('http://path/to/download'); @@ -245,10 +233,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '7.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '7.0.0' } } }, }, }); const res = await supertest @@ -282,10 +268,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - unenrolled_at: new Date().toISOString(), - }, + doc: { + unenrolled_at: new Date().toISOString(), }, }); const res = await supertest @@ -323,10 +307,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); // attempt to upgrade agent in hosted agent policy @@ -348,10 +330,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertestWithoutAuth @@ -369,15 +349,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -404,15 +382,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -433,15 +409,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -462,15 +436,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { - upgradeable: true, - upgraded_at: new Date(Date.now() - 11 * 6e4).toString(), - version: '0.0.0', - }, + doc: { + local_metadata: { + elastic: { + agent: { + upgradeable: true, + upgraded_at: new Date(Date.now() - 11 * 6e4).toString(), + version: '0.0.0', }, }, }, @@ -490,15 +462,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgrade_started_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgrade_started_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -520,15 +490,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgrade_started_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgrade_started_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -549,21 +517,19 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, - upgrade_details: { - target_version: fleetServerVersion, - action_id: 'XXX', - state: 'UPG_REQUESTED', - }, + }, + upgrade_details: { + target_version: fleetServerVersion, + action_id: 'XXX', + state: 'UPG_REQUESTED', }, }, }); @@ -583,21 +549,19 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, - upgrade_details: { - target_version: fleetServerVersion, - action_id: 'XXX', - state: 'UPG_REQUESTED', - }, + }, + upgrade_details: { + target_version: fleetServerVersion, + action_id: 'XXX', + state: 'UPG_REQUESTED', }, }, }); @@ -616,23 +580,21 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, - upgrade_details: { - target_version: fleetServerVersion, - action_id: 'XXX', - state: 'UPG_FAILED', - metadata: { - error_msg: 'Upgrade timed out', - }, + }, + upgrade_details: { + target_version: fleetServerVersion, + action_id: 'XXX', + state: 'UPG_FAILED', + metadata: { + error_msg: 'Upgrade timed out', }, }, }, @@ -651,10 +613,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); const agentBuildVersion = '7.16.0+build20240116'; @@ -668,9 +628,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; @@ -711,18 +669,16 @@ export default function (providerContext: FtrProviderContext) { await es.updateByQuery({ index: '.fleet-agents', - body: { - script: "ctx._source.remove('upgrade_started_at')", - query: { - bool: { - must: [ - { - exists: { - field: 'upgrade_started_at', - }, + script: "ctx._source.remove('upgrade_started_at')", + query: { + bool: { + must: [ + { + exists: { + field: 'upgrade_started_at', }, - ], - }, + }, + ], }, }, }); @@ -733,15 +689,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -766,15 +720,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -802,20 +754,16 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); const agentBuildVersion = '7.16.0+build20240116'; @@ -830,9 +778,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; @@ -844,22 +790,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: false, version: '0.0.0' }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: false, version: '0.0.0' }, }, }, }, @@ -886,20 +828,16 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -914,9 +852,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; @@ -931,20 +867,16 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -959,9 +891,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; @@ -976,25 +906,21 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: false, version: '0.0.0' }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: false, version: '0.0.0' }, }, - upgrade_started_at: undefined, }, + upgrade_started_at: undefined, }, }); await supertest @@ -1018,20 +944,16 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); @@ -1088,20 +1010,16 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -1124,22 +1042,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - unenrolled_at: new Date().toISOString(), - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + unenrolled_at: new Date().toISOString(), + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { agent: { upgradeable: true, version: '0.0.0' } }, - }, + doc: { + local_metadata: { + elastic: { agent: { upgradeable: true, version: '0.0.0' } }, }, }, }); @@ -1164,22 +1078,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: true, version: semver.inc(kibanaVersion, 'patch') }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: true, version: semver.inc(kibanaVersion, 'patch') }, }, }, }, @@ -1188,10 +1098,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent3', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: false, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: false, version: '0.0.0' } } }, }, }); await supertest @@ -1216,15 +1124,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 11 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 11 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -1234,15 +1140,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -1268,15 +1172,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 11 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 11 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -1286,15 +1188,13 @@ export default function (providerContext: FtrProviderContext) { id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), - local_metadata: { - elastic: { - agent: { - upgradeable: true, - version: '0.0.0', - }, + doc: { + upgraded_at: new Date(Date.now() - 9 * 6e4).toISOString(), + local_metadata: { + elastic: { + agent: { + upgradeable: true, + version: '0.0.0', }, }, }, @@ -1321,22 +1221,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: true, version: semver.inc(fleetServerVersion, 'patch') }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: true, version: semver.inc(fleetServerVersion, 'patch') }, }, }, }, @@ -1345,10 +1241,8 @@ export default function (providerContext: FtrProviderContext) { id: 'agent3', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: false, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: false, version: '0.0.0' } } }, }, }); await supertest @@ -1376,22 +1270,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: `agent-policy-1`, - local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, - }, + doc: { + policy_id: `agent-policy-1`, + local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: `agent-policy-2`, - local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, - }, + doc: { + policy_id: `agent-policy-2`, + local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, }, }); await supertest @@ -1410,22 +1300,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: `agent-policy-1`, - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + policy_id: `agent-policy-1`, + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: `agent-policy-2`, - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + policy_id: `agent-policy-2`, + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await supertest @@ -1443,22 +1329,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: `agent-policy-1`, - local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, - }, + doc: { + policy_id: `agent-policy-1`, + local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - policy_id: `agent-policy-2`, - local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, - }, + doc: { + policy_id: `agent-policy-2`, + local_metadata: { elastic: { agent: { upgradeable: true, version: '6.0.0' } } }, }, }); await supertest @@ -1482,22 +1364,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: false, version: '0.0.0' }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: false, version: '0.0.0' }, }, }, }, @@ -1514,9 +1392,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; @@ -1539,22 +1415,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: true, version: '0.0.0' }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: true, version: '0.0.0' }, }, }, }, @@ -1596,22 +1468,18 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { - elastic: { - agent: { upgradeable: true, version: fleetServerVersion }, - }, + doc: { + local_metadata: { + elastic: { + agent: { upgradeable: true, version: fleetServerVersion }, }, }, }, @@ -1639,20 +1507,16 @@ export default function (providerContext: FtrProviderContext) { id: 'agent1', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); await es.update({ id: 'agent2', refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version: '0.0.0' } } }, }, }); const today = new Date(Date.now()); @@ -1668,9 +1532,7 @@ export default function (providerContext: FtrProviderContext) { const actionsRes = await es.search({ index: '.fleet-actions', - body: { - sort: [{ '@timestamp': { order: 'desc' } }], - }, + sort: [{ '@timestamp': { order: 'desc' } }], }); const action: any = actionsRes.hits.hits[0]._source; diff --git a/x-pack/test/fleet_api_integration/apis/agents/uploads.ts b/x-pack/test/fleet_api_integration/apis/agents/uploads.ts index 6ffc84c79bc9d..c6fedce82c68e 100644 --- a/x-pack/test/fleet_api_integration/apis/agents/uploads.ts +++ b/x-pack/test/fleet_api_integration/apis/agents/uploads.ts @@ -75,7 +75,7 @@ export default function (providerContext: FtrProviderContext) { index: AGENT_ACTIONS_INDEX, refresh: true, op_type: 'create', - body: { + document: { type: 'REQUEST_DIAGNOSTICS', action_id: `fleet_uploads_test-${fileName}-action`, agents: [opts.agentId], @@ -91,7 +91,7 @@ export default function (providerContext: FtrProviderContext) { index: AGENT_ACTIONS_RESULTS_INDEX, refresh: true, op_type: 'create', - body: { + document: { action_id: `fleet_uploads_test-${fileName}-action`, agent_id: opts.agentId, '@timestamp': opts.timestamp, @@ -114,7 +114,7 @@ export default function (providerContext: FtrProviderContext) { id: fileName, refresh: true, op_type: 'create', - body: { + document: { '@timestamp': opts.timestamp, upload_id: fileName, action_id: `fleet_uploads_test-${fileName}-action`, @@ -142,7 +142,7 @@ export default function (providerContext: FtrProviderContext) { id: `${fileName}.0`, op_type: 'create', refresh: true, - body: { + document: { '@timestamp': opts.timestamp, last: true, bid: fileName, diff --git a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts index 686532f8eae50..b334387f1d45b 100644 --- a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts +++ b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts @@ -250,15 +250,13 @@ export default function (providerContext: FtrProviderContext) { apiResponse.item.api_key ).security.hasPrivileges( { - body: { - cluster: ['all', 'monitor', 'manage_api_key'], - index: [ - { - names: ['log-*', 'metrics-*', 'events-*', '*'], - privileges: ['write', 'create_index'], - }, - ], - }, + cluster: ['all', 'monitor', 'manage_api_key'], + index: [ + { + names: ['log-*', 'metrics-*', 'events-*', '*'], + privileges: ['write', 'create_index'], + }, + ], }, { meta: true } ); diff --git a/x-pack/test/fleet_api_integration/apis/epm/custom_ingest_pipeline.ts b/x-pack/test/fleet_api_integration/apis/epm/custom_ingest_pipeline.ts index 684000fb95ca0..ce60667aedee4 100644 --- a/x-pack/test/fleet_api_integration/apis/epm/custom_ingest_pipeline.ts +++ b/x-pack/test/fleet_api_integration/apis/epm/custom_ingest_pipeline.ts @@ -58,7 +58,7 @@ export default function (providerContext: FtrProviderContext) { it('Should write doc correctly', async () => { const res = await es.index({ index: 'logs-log.log-test', - body: { + document: { '@timestamp': '2020-01-01T09:09:00', message: 'hello', }, @@ -141,7 +141,7 @@ export default function (providerContext: FtrProviderContext) { it('Should write doc correctly', async () => { const res = await es.index({ index: 'logs-log.log-test', - body: { + document: { '@timestamp': '2020-01-01T09:09:00', message: 'hello', }, diff --git a/x-pack/test/fleet_api_integration/apis/epm/final_pipeline.ts b/x-pack/test/fleet_api_integration/apis/epm/final_pipeline.ts index 5bb2ad4f9d5c5..5f6e528e85078 100644 --- a/x-pack/test/fleet_api_integration/apis/epm/final_pipeline.ts +++ b/x-pack/test/fleet_api_integration/apis/epm/final_pipeline.ts @@ -69,17 +69,15 @@ export default function (providerContext: FtrProviderContext) { it('should correctly update the final pipeline', async () => { await es.ingest.putPipeline({ id: FINAL_PIPELINE_ID, - body: { - description: 'Test PIPELINE WITHOUT version', - processors: [ - { - set: { - field: 'my-keyword-field', - value: 'foo', - }, + description: 'Test PIPELINE WITHOUT version', + processors: [ + { + set: { + field: 'my-keyword-field', + value: 'foo', }, - ], - }, + }, + ], }); await supertest.post(`/api/fleet/setup`).set('kbn-xsrf', 'xxxx'); const pipelineRes = await es.ingest.getPipeline({ id: FINAL_PIPELINE_ID }); @@ -102,7 +100,7 @@ export default function (providerContext: FtrProviderContext) { it('all docs should contain event.ingested without sub-seconds', async () => { const res = await es.index({ index: 'logs-log.log-test', - body: { + document: { '@timestamp': '2020-01-01T09:09:00', message: 'hello', }, @@ -122,7 +120,7 @@ export default function (providerContext: FtrProviderContext) { it('For a doc written without api key should write the correct api key status', async () => { const res = await es.index({ index: 'logs-log.log-test', - body: { + document: { message: 'message-test-1', '@timestamp': '2020-01-01T09:09:00', agent: { @@ -145,7 +143,7 @@ export default function (providerContext: FtrProviderContext) { it('removes event.original if preserve_original_event is not set', async () => { const res = await es.index({ index: 'logs-log.log-test', - body: { + document: { message: 'message-test-1', event: { original: JSON.stringify({ foo: 'bar' }), @@ -171,7 +169,7 @@ export default function (providerContext: FtrProviderContext) { it('preserves event.original if preserve_original_event is set', async () => { const res = await es.index({ index: 'logs-log.log-test', - body: { + document: { message: 'message-test-1', event: { original: JSON.stringify({ foo: 'bar' }), @@ -236,10 +234,8 @@ export default function (providerContext: FtrProviderContext) { // Create an API key const apiKeyRes = await es.security.createApiKey( { - body: { - name: `test api key`, - ...(scenario.apiKey || {}), - }, + name: `test api key`, + ...(scenario.apiKey || {}), }, { headers: { 'es-security-runas-user': 'elastic' }, // run as elastic suer diff --git a/x-pack/test/fleet_api_integration/apis/epm/install_integration_in_multiple_spaces.ts b/x-pack/test/fleet_api_integration/apis/epm/install_integration_in_multiple_spaces.ts index c495c395a5b97..2ae6fce3f9897 100644 --- a/x-pack/test/fleet_api_integration/apis/epm/install_integration_in_multiple_spaces.ts +++ b/x-pack/test/fleet_api_integration/apis/epm/install_integration_in_multiple_spaces.ts @@ -153,11 +153,9 @@ export default function (providerContext: FtrProviderContext) { await es.update({ index: INGEST_SAVED_OBJECT_INDEX, id: `${PACKAGES_SAVED_OBJECT_TYPE}:${nginxPkgName}`, - body: { - doc: { - [PACKAGES_SAVED_OBJECT_TYPE]: { - install_format_schema_version: '99.99.99', - }, + doc: { + [PACKAGES_SAVED_OBJECT_TYPE]: { + install_format_schema_version: '99.99.99', }, }, }); diff --git a/x-pack/test/fleet_api_integration/apis/epm/routing_rules.ts b/x-pack/test/fleet_api_integration/apis/epm/routing_rules.ts index 397fb98d2b346..a55fdb8f7c1dc 100644 --- a/x-pack/test/fleet_api_integration/apis/epm/routing_rules.ts +++ b/x-pack/test/fleet_api_integration/apis/epm/routing_rules.ts @@ -59,7 +59,7 @@ export default function (providerContext: FtrProviderContext) { it('Should write doc correctly and apply the routing rule', async () => { const res = await es.index({ index: TEST_WRITE_INDEX, - body: { + document: { '@timestamp': '2020-01-01T09:09:00', message: 'hello', data_stream: { diff --git a/x-pack/test/fleet_api_integration/apis/event_ingested/use_event_ingested.ts b/x-pack/test/fleet_api_integration/apis/event_ingested/use_event_ingested.ts index 7badbedbd77ba..51222f509cd6d 100644 --- a/x-pack/test/fleet_api_integration/apis/event_ingested/use_event_ingested.ts +++ b/x-pack/test/fleet_api_integration/apis/event_ingested/use_event_ingested.ts @@ -63,17 +63,15 @@ export default function (providerContext: FtrProviderContext) { it('should correctly update the event ingested pipeline', async () => { await es.ingest.putPipeline({ id: FLEET_EVENT_INGESTED_PIPELINE_ID, - body: { - description: 'Test PIPELINE WITHOUT version', - processors: [ - { - set: { - field: 'my-keyword-field', - value: 'foo', - }, + description: 'Test PIPELINE WITHOUT version', + processors: [ + { + set: { + field: 'my-keyword-field', + value: 'foo', }, - ], - }, + }, + ], }); await supertestWithoutAuth .post(`/api/fleet/setup`) diff --git a/x-pack/test/fleet_api_integration/apis/outputs/crud.ts b/x-pack/test/fleet_api_integration/apis/outputs/crud.ts index 7d2e9ed7930c1..b58fc37086c15 100644 --- a/x-pack/test/fleet_api_integration/apis/outputs/crud.ts +++ b/x-pack/test/fleet_api_integration/apis/outputs/crud.ts @@ -36,10 +36,8 @@ export default function (providerContext: FtrProviderContext) { try { await es.deleteByQuery({ index: '.fleet-secrets', - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); } catch (err) { @@ -85,7 +83,7 @@ export default function (providerContext: FtrProviderContext) { const agentResponse = await es.index({ index: '.fleet-agents', refresh: true, - body: { + document: { access_api_key_id: 'api-key-3', active: true, policy_id: agentPolicyId, @@ -109,10 +107,8 @@ export default function (providerContext: FtrProviderContext) { await es.deleteByQuery({ index: '.fleet-agents', refresh: true, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); } catch (err) { diff --git a/x-pack/test/fleet_api_integration/apis/outputs/logstash_api_keys.ts b/x-pack/test/fleet_api_integration/apis/outputs/logstash_api_keys.ts index 24d596e40f36e..448918e66d20f 100644 --- a/x-pack/test/fleet_api_integration/apis/outputs/logstash_api_keys.ts +++ b/x-pack/test/fleet_api_integration/apis/outputs/logstash_api_keys.ts @@ -30,22 +30,20 @@ export default function (providerContext: FtrProviderContext) { Buffer.from(apiKeyRes.api_key).toString('base64') ).security.hasPrivileges( { - body: { - cluster: ['monitor'], - index: [ - { - names: [ - 'logs-*-*', - 'metrics-*-*', - 'traces-*-*', - 'synthetics-*-*', - '.logs-endpoint.diagnostic.collection-*', - '.logs-endpoint.action.responses-*', - ], - privileges: ['auto_configure', 'create_doc'], - }, - ], - }, + cluster: ['monitor'], + index: [ + { + names: [ + 'logs-*-*', + 'metrics-*-*', + 'traces-*-*', + 'synthetics-*-*', + '.logs-endpoint.diagnostic.collection-*', + '.logs-endpoint.action.responses-*', + ], + privileges: ['auto_configure', 'create_doc'], + }, + ], }, { meta: true } ); diff --git a/x-pack/test/fleet_api_integration/apis/package_policy/input_package_create_upgrade.ts b/x-pack/test/fleet_api_integration/apis/package_policy/input_package_create_upgrade.ts index bbd55641ce916..9758f20b5945c 100644 --- a/x-pack/test/fleet_api_integration/apis/package_policy/input_package_create_upgrade.ts +++ b/x-pack/test/fleet_api_integration/apis/package_policy/input_package_create_upgrade.ts @@ -154,7 +154,7 @@ export default function (providerContext: FtrProviderContext) { await es.index({ index: indexName, - body: { + document: { '@timestamp': new Date().toISOString(), message: 'test', }, diff --git a/x-pack/test/fleet_api_integration/apis/policy_secrets.ts b/x-pack/test/fleet_api_integration/apis/policy_secrets.ts index 33fa7844d343e..258f235813e4e 100644 --- a/x-pack/test/fleet_api_integration/apis/policy_secrets.ts +++ b/x-pack/test/fleet_api_integration/apis/policy_secrets.ts @@ -112,19 +112,15 @@ export default function (providerContext: FtrProviderContext) { es.deleteByQuery({ index: ENROLLMENT_API_KEYS_INDEX, refresh: true, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }), es.deleteByQuery({ index: AGENT_POLICY_INDEX, refresh: true, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }), ]).catch((err) => { @@ -137,10 +133,8 @@ export default function (providerContext: FtrProviderContext) { await es.deleteByQuery({ index: AGENTS_INDEX, refresh: true, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); } catch (err) { @@ -153,10 +147,8 @@ export default function (providerContext: FtrProviderContext) { await es.deleteByQuery({ index: SECRETS_INDEX_NAME, refresh: true, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); } catch (err) { @@ -254,7 +246,7 @@ export default function (providerContext: FtrProviderContext) { const agentResponse = await es.index({ index: '.fleet-agents', refresh: true, - body: { + document: { access_api_key_id: 'api-key-3', active: true, policy_id: policyId, @@ -283,9 +275,7 @@ export default function (providerContext: FtrProviderContext) { const query = ids ? { terms: { _id: ids } } : { match_all: {} }; return es.search({ index: SECRETS_INDEX_NAME, - body: { - query, - }, + query, }); }; @@ -302,27 +292,25 @@ export default function (providerContext: FtrProviderContext) { const getLatestPolicyRevision = async (id: string): Promise<{ data: FullAgentPolicy }> => { const res = await es.search({ index: '.fleet-policies', - body: { - query: { - bool: { - filter: [ - { - term: { - policy_id: id, - }, + query: { + bool: { + filter: [ + { + term: { + policy_id: id, }, - ], - }, - }, - sort: [ - { - revision_idx: { - order: 'desc', }, - }, - ], - size: 1, + ], + }, }, + sort: [ + { + revision_idx: { + order: 'desc', + }, + }, + ], + size: 1, }); return res.hits.hits[0]._source as any as { data: FullAgentPolicy }; }; diff --git a/x-pack/test/fleet_api_integration/apis/space_awareness/helpers.ts b/x-pack/test/fleet_api_integration/apis/space_awareness/helpers.ts index e4e5ff2563cc1..1a9892fd386a2 100644 --- a/x-pack/test/fleet_api_integration/apis/space_awareness/helpers.ts +++ b/x-pack/test/fleet_api_integration/apis/space_awareness/helpers.ts @@ -102,7 +102,7 @@ export async function createFleetAgent(esClient: Client, agentPolicyId: string, const agentResponse = await esClient.index({ index: '.fleet-agents', refresh: true, - body: { + document: { access_api_key_id: 'api-key-3', active: true, policy_id: agentPolicyId, @@ -139,10 +139,8 @@ export async function makeAgentsUpgradeable(esClient: Client, agentIds: string[] id: agentId, refresh: 'wait_for', index: AGENTS_INDEX, - body: { - doc: { - local_metadata: { elastic: { agent: { upgradeable: true, version } } }, - }, + doc: { + local_metadata: { elastic: { agent: { upgradeable: true, version } } }, }, }); }); diff --git a/x-pack/test/fleet_api_integration/helpers.ts b/x-pack/test/fleet_api_integration/helpers.ts index 0cdb86e0ef518..8e2da32241b4a 100644 --- a/x-pack/test/fleet_api_integration/helpers.ts +++ b/x-pack/test/fleet_api_integration/helpers.ts @@ -107,7 +107,7 @@ export async function generateAgent( await es.index({ index: '.fleet-agents', id, - body: { + document: { id, active: true, last_checkin: new Date().toISOString(), diff --git a/x-pack/test/functional/apps/canvas/reports.ts b/x-pack/test/functional/apps/canvas/reports.ts index 880a8573991d0..fedcc5a116148 100644 --- a/x-pack/test/functional/apps/canvas/reports.ts +++ b/x-pack/test/functional/apps/canvas/reports.ts @@ -40,7 +40,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.deleteByQuery({ index: '.reporting-*', refresh: true, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); }); diff --git a/x-pack/test/functional/apps/dashboard/group3/reporting/screenshots.ts b/x-pack/test/functional/apps/dashboard/group3/reporting/screenshots.ts index 30a715dc472a7..3e899e6f0419e 100644 --- a/x-pack/test/functional/apps/dashboard/group3/reporting/screenshots.ts +++ b/x-pack/test/functional/apps/dashboard/group3/reporting/screenshots.ts @@ -75,7 +75,7 @@ export default function ({ await es.deleteByQuery({ index: '.reporting-*', refresh: true, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); await security.testUser.restoreDefaults(); }); diff --git a/x-pack/test/functional/apps/discover/reporting.ts b/x-pack/test/functional/apps/discover/reporting.ts index 0842bc9d5fc73..177f3c92e94e1 100644 --- a/x-pack/test/functional/apps/discover/reporting.ts +++ b/x-pack/test/functional/apps/discover/reporting.ts @@ -234,7 +234,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const res = await es.bulk({ index: TEST_INDEX_NAME, - body: docs.map((d) => `{"index": {}}\n${JSON.stringify(d)}\n`), + operations: docs.map((d) => `{"index": {}}\n${JSON.stringify(d)}\n`), }); log.info(`Indexed ${res.items.length} test data docs.`); diff --git a/x-pack/test/functional/apps/index_management/create_enrich_policy/create_enrich_policy.ts b/x-pack/test/functional/apps/index_management/create_enrich_policy/create_enrich_policy.ts index 3d0a1e562e45b..3640ef1008d13 100644 --- a/x-pack/test/functional/apps/index_management/create_enrich_policy/create_enrich_policy.ts +++ b/x-pack/test/functional/apps/index_management/create_enrich_policy/create_enrich_policy.ts @@ -25,15 +25,13 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { try { await es.indices.create({ index: INDEX_NAME, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - age: { - type: 'long', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + age: { + type: 'long', }, }, }, diff --git a/x-pack/test/functional/apps/index_management/data_streams_tab/data_streams_tab.ts b/x-pack/test/functional/apps/index_management/data_streams_tab/data_streams_tab.ts index ae32297fe96a0..0050161a7464e 100644 --- a/x-pack/test/functional/apps/index_management/data_streams_tab/data_streams_tab.ts +++ b/x-pack/test/functional/apps/index_management/data_streams_tab/data_streams_tab.ts @@ -49,7 +49,6 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }, }, lifecycle: { - // @ts-expect-error @elastic/elasticsearch enabled prop is not typed yet enabled: true, }, }, diff --git a/x-pack/test/functional/apps/index_management/enrich_policies_tab/enrich_policies_tab.ts b/x-pack/test/functional/apps/index_management/enrich_policies_tab/enrich_policies_tab.ts index 0d090835139dd..6f692c645256d 100644 --- a/x-pack/test/functional/apps/index_management/enrich_policies_tab/enrich_policies_tab.ts +++ b/x-pack/test/functional/apps/index_management/enrich_policies_tab/enrich_policies_tab.ts @@ -32,12 +32,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { try { await es.indices.create({ index: ENRICH_INDEX_NAME, - body: { - mappings: { - properties: { - name: { - type: 'text', - }, + mappings: { + properties: { + name: { + type: 'text', }, }, }, diff --git a/x-pack/test/functional/apps/index_management/index_templates_tab/index_template_tab.ts b/x-pack/test/functional/apps/index_management/index_templates_tab/index_template_tab.ts index 003e7e38c00a5..48a7d51080748 100644 --- a/x-pack/test/functional/apps/index_management/index_templates_tab/index_template_tab.ts +++ b/x-pack/test/functional/apps/index_management/index_templates_tab/index_template_tab.ts @@ -236,12 +236,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await es.indices.putIndexTemplate({ name: TEST_TEMPLATE, - body: { - index_patterns: [INDEX_PATTERN], - template: { - settings: { - default_pipeline: 'test_pipeline', - }, + index_patterns: [INDEX_PATTERN], + template: { + settings: { + default_pipeline: 'test_pipeline', }, }, }); diff --git a/x-pack/test/functional/apps/ingest_pipelines/ingest_pipelines.ts b/x-pack/test/functional/apps/ingest_pipelines/ingest_pipelines.ts index fa66399c09c79..8efbb124ac094 100644 --- a/x-pack/test/functional/apps/ingest_pipelines/ingest_pipelines.ts +++ b/x-pack/test/functional/apps/ingest_pipelines/ingest_pipelines.ts @@ -53,7 +53,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { // Create a test pipeline await es.ingest.putPipeline({ id: TEST_PIPELINE_NAME, - body: { processors: [] }, + processors: [], } as IngestPutPipelineRequest); }); diff --git a/x-pack/test/functional/apps/lens/group3/terms.ts b/x-pack/test/functional/apps/lens/group3/terms.ts index 5c7f2c8669381..8ffad5329aec6 100644 --- a/x-pack/test/functional/apps/lens/group3/terms.ts +++ b/x-pack/test/functional/apps/lens/group3/terms.ts @@ -245,7 +245,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.bulk({ index: esIndexPrefix, - body: Array<{ + operations: Array<{ a: string; b: string; '@timestamp': string; diff --git a/x-pack/test/functional/apps/lens/group6/lens_reporting.ts b/x-pack/test/functional/apps/lens/group6/lens_reporting.ts index f3bde620f21f9..f1b15a404834b 100644 --- a/x-pack/test/functional/apps/lens/group6/lens_reporting.ts +++ b/x-pack/test/functional/apps/lens/group6/lens_reporting.ts @@ -60,7 +60,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.deleteByQuery({ index: '.reporting-*', refresh: true, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); await security.testUser.restoreDefaults(); }); diff --git a/x-pack/test/functional/apps/lens/tsdb_logsdb_helpers.ts b/x-pack/test/functional/apps/lens/tsdb_logsdb_helpers.ts index d68040de27ae9..b0a78cb06e812 100644 --- a/x-pack/test/functional/apps/lens/tsdb_logsdb_helpers.ts +++ b/x-pack/test/functional/apps/lens/tsdb_logsdb_helpers.ts @@ -309,7 +309,9 @@ export const getDocsGenerator = const result = await es.bulk( { index: esIndex, - body: docs.map((d) => `{"${isStream ? 'create' : 'index'}": {}}\n${JSON.stringify(d)}\n`), + operations: docs.map( + (d) => `{"${isStream ? 'create' : 'index'}": {}}\n${JSON.stringify(d)}\n` + ), }, { meta: true } ); diff --git a/x-pack/test/functional/apps/remote_clusters/ccs/remote_clusters_index_management_flow.ts b/x-pack/test/functional/apps/remote_clusters/ccs/remote_clusters_index_management_flow.ts index 4f710b3730353..d00e7a9cb6f7f 100644 --- a/x-pack/test/functional/apps/remote_clusters/ccs/remote_clusters_index_management_flow.ts +++ b/x-pack/test/functional/apps/remote_clusters/ccs/remote_clusters_index_management_flow.ts @@ -56,9 +56,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await remoteEs.indices.create({ index: leaderName, - body: { - settings: { number_of_shards: 1, soft_deletes: { enabled: true } }, - }, + settings: { number_of_shards: 1, soft_deletes: { enabled: true } }, }); await pageObjects.common.navigateToApp('crossClusterReplication'); await retry.waitFor('indices table to be visible', async () => { @@ -79,7 +77,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await remoteEs.index({ index: leaderName, - body: { a: 'b' }, + document: { a: 'b' }, }); await pageObjects.common.navigateToApp('indexManagement'); await retry.waitForWithTimeout('indices table to be visible', 15000, async () => { diff --git a/x-pack/test/functional/apps/rollup_job/tsvb.js b/x-pack/test/functional/apps/rollup_job/tsvb.js index 1220e3c51845a..4a852d60c27c2 100644 --- a/x-pack/test/functional/apps/rollup_job/tsvb.js +++ b/x-pack/test/functional/apps/rollup_job/tsvb.js @@ -58,7 +58,7 @@ export default function ({ getService, getPageObjects }) { //Create data for rollup job so it doesn't fail await es.index({ index: rollupSourceIndexName, - body: { + document: { '@timestamp': new Date().toISOString(), }, }); diff --git a/x-pack/test/functional/apps/upgrade_assistant/deprecation_pages.ts b/x-pack/test/functional/apps/upgrade_assistant/deprecation_pages.ts index 00c8771670b44..08d9e55ecc0f0 100644 --- a/x-pack/test/functional/apps/upgrade_assistant/deprecation_pages.ts +++ b/x-pack/test/functional/apps/upgrade_assistant/deprecation_pages.ts @@ -33,11 +33,9 @@ export default function upgradeAssistantFunctionalTests({ * on both local and CI environments. */ await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - max_shards_per_node: 5, - }, + persistent: { + cluster: { + max_shards_per_node: 5, }, }, }); @@ -50,12 +48,10 @@ export default function upgradeAssistantFunctionalTests({ after(async () => { try { await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - // initial cluster setting from x-pack/test/functional/config.upgrade_assistant.js - max_shards_per_node: 29, - }, + persistent: { + cluster: { + // initial cluster setting from x-pack/test/functional/config.upgrade_assistant.js + max_shards_per_node: 29, }, }, }); diff --git a/x-pack/test/functional/apps/visualize/reporting.ts b/x-pack/test/functional/apps/visualize/reporting.ts index 0e08bea2990d7..ac77599b3eb85 100644 --- a/x-pack/test/functional/apps/visualize/reporting.ts +++ b/x-pack/test/functional/apps/visualize/reporting.ts @@ -38,7 +38,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.deleteByQuery({ index: '.reporting-*', refresh: true, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); }); @@ -62,7 +62,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.deleteByQuery({ index: '.reporting-*', refresh: true, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }); await kibanaServer.uiSettings.unset('timepicker:timeDefaults'); }); diff --git a/x-pack/test/functional/page_objects/observability_logs_explorer.ts b/x-pack/test/functional/page_objects/observability_logs_explorer.ts index 3f71add1fbc56..10b0d9b4efd78 100644 --- a/x-pack/test/functional/page_objects/observability_logs_explorer.ts +++ b/x-pack/test/functional/page_objects/observability_logs_explorer.ts @@ -168,7 +168,7 @@ export function ObservabilityLogsExplorerPageObject({ ingestLogEntries(dataStream: string, docs: MockLogDoc[] = []) { log.info(`===== Ingesting ${docs.length} docs for "${dataStream}" data stream. =====`); return es.bulk({ - body: docs.flatMap((doc) => [{ create: { _index: dataStream } }, createLogDoc(doc)]), + operations: docs.flatMap((doc) => [{ create: { _index: dataStream } }, createLogDoc(doc)]), refresh: 'wait_for', }); }, diff --git a/x-pack/test/functional/services/aiops/log_rate_analysis_data_generator.ts b/x-pack/test/functional/services/aiops/log_rate_analysis_data_generator.ts index ffc007a6d73c6..2cc7ec0cad82a 100644 --- a/x-pack/test/functional/services/aiops/log_rate_analysis_data_generator.ts +++ b/x-pack/test/functional/services/aiops/log_rate_analysis_data_generator.ts @@ -5,7 +5,7 @@ * 2.0. */ -import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { LOG_RATE_ANALYSIS_TYPE } from '@kbn/aiops-log-rate-analysis'; @@ -58,7 +58,7 @@ function getArtificialLogsWithDeviation( includeTextField = false, includeGaps = false ) { - const bulkBody: estypes.BulkRequest['body'] = []; + const bulkBody: estypes.BulkRequest['operations'] = []; const action = { index: { _index: index } }; let tsOffset = 0; @@ -237,18 +237,16 @@ export function LogRateAnalysisDataGeneratorProvider({ getService }: FtrProvider await es.updateByQuery({ index: 'ft_farequote', - body: { - script: { - // @ts-expect-error - inline: 'ctx._source.custom_field = "default"', - lang: 'painless', - }, + script: { + // @ts-expect-error + inline: 'ctx._source.custom_field = "default"', + lang: 'painless', }, }); await es.bulk({ refresh: 'wait_for', - body: [...Array(100)].flatMap((i) => { + operations: [...Array(100)].flatMap((i) => { return [ { index: { _index: 'ft_farequote' } }, { @@ -312,7 +310,7 @@ export function LogRateAnalysisDataGeneratorProvider({ getService }: FtrProvider await es.bulk({ refresh: 'wait_for', - body: getArtificialLogsWithDeviation( + operations: getArtificialLogsWithDeviation( dataGenerator, deviationType, textField, diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index 3d2d1004528d0..90c2a65d77a1f 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import expect from '@kbn/expect'; import { ProvidedType } from '@kbn/test'; import type { TypeOf } from '@kbn/config-schema'; @@ -99,12 +99,10 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async hasJobResults(jobId: string): Promise { const body = await es.search({ index: '.ml-anomalies-*', - body: { - size: 1, - query: { - match: { - job_id: jobId, - }, + size: 1, + query: { + match: { + job_id: jobId, }, }, }); @@ -139,28 +137,26 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async hasDetectorResults(jobId: string, detectorIndex: number): Promise { const body = await es.search({ index: '.ml-anomalies-*', - body: { - size: 1, - query: { - bool: { - must: [ - { - match: { - job_id: jobId, - }, + size: 1, + query: { + bool: { + must: [ + { + match: { + job_id: jobId, }, - { - match: { - result_type: 'record', - }, + }, + { + match: { + result_type: 'record', }, - { - match: { - detector_index: detectorIndex, - }, + }, + { + match: { + detector_index: detectorIndex, }, - ], - }, + }, + ], }, }, }); @@ -187,23 +183,21 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async hasForecastResults(jobId: string): Promise { const body = await es.search({ index: '.ml-anomalies-*', - body: { - size: 1, - query: { - bool: { - must: [ - { - match: { - job_id: jobId, - }, + size: 1, + query: { + bool: { + must: [ + { + match: { + job_id: jobId, }, - { - match: { - result_type: 'model_forecast', - }, + }, + { + match: { + result_type: 'model_forecast', }, - ], - }, + }, + ], }, }, }); @@ -278,10 +272,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { const body = await es.indices.create({ index: indices, - body: { - ...(mappings ? { mappings } : {}), - ...(settings ? { settings } : {}), - }, + ...(mappings ? { mappings } : {}), + ...(settings ? { settings } : {}), }); expect(body) .to.have.property('acknowledged') @@ -546,9 +538,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { await retry.tryForTime(30 * 1000, async () => { const body = await es.search({ index: indices, - body: { - size: 1, - }, + size: 1, }); if (body.hits.hits.length > 0) { @@ -761,10 +751,8 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async hasNotifications(query: object) { const body = await es.search({ index: '.ml-notifications*', - body: { - size: 10000, - query, - }, + size: 10000, + query, }); return body.hits.hits.length > 0; @@ -1281,11 +1269,9 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { const body = await es.search({ index: ML_ANNOTATIONS_INDEX_ALIAS_READ, - body: { - query: { - match: { - job_id: jobId, - }, + query: { + match: { + job_id: jobId, }, }, }); @@ -1319,12 +1305,10 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { const body = await es.search({ index: ML_ANNOTATIONS_INDEX_ALIAS_READ, - body: { - size: 1, - query: { - match: { - _id: annotationId, - }, + size: 1, + query: { + match: { + _id: annotationId, }, }, }); @@ -1343,7 +1327,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { const params = { index: ML_ANNOTATIONS_INDEX_ALIAS_WRITE, id, - body: annotationRequestBody, + document: annotationRequestBody, refresh: 'wait_for', } as const; const body = await es.index(params); @@ -1797,7 +1781,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { const params = { index: '.ml-stats-000001', id: 'noop_job_test_id', - body: { + document: { type: 'analytics_memory_usage', job_id: 'noop_job', timestamp: 1687437633705, diff --git a/x-pack/test/functional/services/ml/data_visualizer_file_based.ts b/x-pack/test/functional/services/ml/data_visualizer_file_based.ts index d9d59e000d805..09b79982039aa 100644 --- a/x-pack/test/functional/services/ml/data_visualizer_file_based.ts +++ b/x-pack/test/functional/services/ml/data_visualizer_file_based.ts @@ -192,11 +192,9 @@ export function MachineLearningDataVisualizerFileBasedProvider( async getDocCountFromIndex(index: string) { const resp = await es.search({ index, - body: { - size: 0, - query: { - match_all: {}, - }, + size: 0, + query: { + match_all: {}, }, }); // @ts-expect-error incorrect type definition diff --git a/x-pack/test/functional/services/transform/api.ts b/x-pack/test/functional/services/transform/api.ts index 66047a651a891..fc7b35b682ed9 100644 --- a/x-pack/test/functional/services/transform/api.ts +++ b/x-pack/test/functional/services/transform/api.ts @@ -14,7 +14,7 @@ import type { TransformStats } from '@kbn/transform-plugin/common/types/transfor import type { GetTransformsResponseSchema } from '@kbn/transform-plugin/server/routes/api_schemas/transforms'; import type { PostTransformsUpdateRequestSchema } from '@kbn/transform-plugin/server/routes/api_schemas/update_transforms'; import type { TransformPivotConfig } from '@kbn/transform-plugin/common/types/transform'; -import type { IndicesCreateRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { IndicesCreateRequest } from '@elastic/elasticsearch/lib/api/types'; import type { FtrProviderContext } from '../../ftr_provider_context'; export async function asyncForEach(array: any[], callback: Function) { @@ -42,7 +42,9 @@ export function TransformAPIProvider({ getService }: FtrProviderContext) { async createIndices( indices: string, - params: IndicesCreateRequest['body'] = {} as NonNullable + params: Omit = {} as NonNullable< + Omit + > ) { log.debug(`Creating indices: '${indices}'...`); if ((await es.indices.exists({ index: indices, allow_no_indices: false })) === true) { diff --git a/x-pack/test/functional/services/transform/security_common.ts b/x-pack/test/functional/services/transform/security_common.ts index d7eb3e64de4dc..adaee9d88370f 100644 --- a/x-pack/test/functional/services/transform/security_common.ts +++ b/x-pack/test/functional/services/transform/security_common.ts @@ -116,11 +116,9 @@ export function TransformSecurityCommonProvider({ getService }: FtrProviderConte return map; }, {}); const apiKey = await esClient.security.createApiKey({ - body: { - name: `Transform API Key ${user.full_name}`, - role_descriptors: roleDescriptors, - metadata: user, - }, + name: `Transform API Key ${user.full_name}`, + role_descriptors: roleDescriptors, + metadata: user, }); return { user: { name: user.name as USER, roles: user.roles }, apiKey }; }, diff --git a/x-pack/test/functional_search/tests/search_index_details.ts b/x-pack/test/functional_search/tests/search_index_details.ts index 4aad814653dcf..683a2a541cd1a 100644 --- a/x-pack/test/functional_search/tests/search_index_details.ts +++ b/x-pack/test/functional_search/tests/search_index_details.ts @@ -118,12 +118,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.searchIndexDetailsPage.expectQuickStatsAIMappings(); await es.indices.putMapping({ index: indexName, - body: { - properties: { - my_field: { - type: 'dense_vector', - dims: 3, - }, + properties: { + my_field: { + type: 'dense_vector', + dims: 3, }, }, }); diff --git a/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/discover/search_source_alert.ts b/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/discover/search_source_alert.ts index 3ce3ea7ba12b6..3777c564296a8 100644 --- a/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/discover/search_source_alert.ts +++ b/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/discover/search_source_alert.ts @@ -66,7 +66,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { try { await es.index({ index, - body: { + document: { settings: { number_of_shards: 1 }, mappings: { properties }, }, diff --git a/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/ml/alert_flyout.ts b/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/ml/alert_flyout.ts index e76093c666ca1..0d14c7aef39af 100644 --- a/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/ml/alert_flyout.ts +++ b/x-pack/test/functional_with_es_ssl/apps/discover_ml_uptime/ml/alert_flyout.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; diff --git a/x-pack/test/plugin_api_integration/plugins/sample_task_plugin/server/plugin.ts b/x-pack/test/plugin_api_integration/plugins/sample_task_plugin/server/plugin.ts index 9604ad6732e58..891df37e76158 100644 --- a/x-pack/test/plugin_api_integration/plugins/sample_task_plugin/server/plugin.ts +++ b/x-pack/test/plugin_api_integration/plugins/sample_task_plugin/server/plugin.ts @@ -70,7 +70,7 @@ export class SampleTaskManagerFixturePlugin const [{ elasticsearch }] = await core.getStartServices(); await elasticsearch.client.asInternalUser.index({ index: '.kibana_task_manager_test_result', - body: { + document: { type: 'task', taskId: taskInstance.id, params: JSON.stringify(runParams), diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/kibana_discovery_service.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/kibana_discovery_service.ts index f944f64147710..bebca8701c44a 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/kibana_discovery_service.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/kibana_discovery_service.ts @@ -17,11 +17,9 @@ export default function createTaskManagementScheduledAtTests({ getService }: Ftr { index: '.kibana_task_manager', size: 100, - body: { - query: { - term: { - type: 'background-task-node', - }, + query: { + term: { + type: 'background-task-node', }, }, }, diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/metrics_route.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/metrics_route.ts index b456e35d5d673..e4572d8245435 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/metrics_route.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/metrics_route.ts @@ -256,13 +256,11 @@ export default function ({ getService }: FtrProviderContext) { // modify the rule to get it fire a decryption error await es.updateByQuery({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - script: { - lang: 'painless', - source: 'ctx._source.alert.params.foo = "bar"', - }, - query: { ids: { values: [`alert:${ruleId}`] } }, + script: { + lang: 'painless', + source: 'ctx._source.alert.params.foo = "bar"', }, + query: { ids: { values: [`alert:${ruleId}`] } }, refresh: true, conflicts: 'proceed', }); @@ -288,13 +286,11 @@ export default function ({ getService }: FtrProviderContext) { // modify the rule to get it fire a validation error await es.updateByQuery({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - script: { - lang: 'painless', - source: 'ctx._source.alert.params.foo = "bar"', - }, - query: { ids: { values: [`alert:${ruleId}`] } }, + script: { + lang: 'painless', + source: 'ctx._source.alert.params.foo = "bar"', }, + query: { ids: { values: [`alert:${ruleId}`] } }, refresh: true, conflicts: 'proceed', }); diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/migrations.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/migrations.ts index b53da1b363bcb..5e776d5e2f3e4 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/migrations.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/migrations.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportResult } from '@elastic/elasticsearch'; import { ConcreteTaskInstance, @@ -61,11 +61,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { > = await es.search( { index: '.kibana_task_manager', - body: { - query: { - term: { - _id: 'task:be7e1250-3322-11eb-94c1-db6995e8389f', - }, + query: { + term: { + _id: 'task:be7e1250-3322-11eb-94c1-db6995e8389f', }, }, }, @@ -90,11 +88,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { > = await es.search( { index: '.kibana_task_manager', - body: { - query: { - term: { - _id: 'task:d33d7590-8377-11ec-8c11-2dfe94229b95', - }, + query: { + term: { + _id: 'task:d33d7590-8377-11ec-8c11-2dfe94229b95', }, }, }, @@ -144,10 +140,8 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, { @@ -171,10 +165,8 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }, { @@ -199,7 +191,7 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }, { meta: true } ); @@ -232,7 +224,7 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { query: { match_all: {} } }, + query: { match_all: {} }, }, { meta: true } ); diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts index 34ef9c2481bc1..a3e58e8282e77 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts @@ -8,7 +8,7 @@ import moment from 'moment'; import { random } from 'lodash'; import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { taskMappings as TaskManagerMapping } from '@kbn/task-manager-plugin/server/saved_objects/mappings'; import { ConcreteTaskInstance, BulkUpdateTaskResult } from '@kbn/task-manager-plugin/server'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -58,25 +58,23 @@ export default function ({ getService }: FtrProviderContext) { await es.deleteByQuery({ index: testHistoryIndex, refresh: true, - body: { query: { term: { type: 'task' } } }, + query: { term: { type: 'task' } }, }); } else { await es.indices.create({ index: testHistoryIndex, - body: { - mappings: { - properties: { - type: { - type: 'keyword', - }, - taskId: { - type: 'keyword', - }, - params: taskManagerIndexMapping.params, - state: taskManagerIndexMapping.state, - runAt: taskManagerIndexMapping.runAt, - } as Record, - }, + mappings: { + properties: { + type: { + type: 'keyword', + }, + taskId: { + type: 'keyword', + }, + params: taskManagerIndexMapping.params, + state: taskManagerIndexMapping.state, + runAt: taskManagerIndexMapping.runAt, + } as Record, }, }); } @@ -134,10 +132,8 @@ export default function ({ getService }: FtrProviderContext) { return es .search({ index: testHistoryIndex, - body: { - query: { - term: { type: 'task' }, - }, + query: { + term: { type: 'task' }, }, }) .then((result) => diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_partitions.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_partitions.ts index 57e7fc107a7b4..e6269d5de4540 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_partitions.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_partitions.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server'; import { taskMappings as TaskManagerMapping } from '@kbn/task-manager-plugin/server/saved_objects/mappings'; import { asyncForEach } from '@kbn/std'; @@ -104,11 +104,9 @@ export default function ({ getService }: FtrProviderContext) { return es .search({ index: testHistoryIndex, - body: { - query: { - bool: { - filter, - }, + query: { + bool: { + filter, }, }, }) @@ -122,25 +120,23 @@ export default function ({ getService }: FtrProviderContext) { await es.deleteByQuery({ index: testHistoryIndex, refresh: true, - body: { query: { term: { type: 'task' } } }, + query: { term: { type: 'task' } }, }); } else { await es.indices.create({ index: testHistoryIndex, - body: { - mappings: { - properties: { - type: { - type: 'keyword', - }, - taskId: { - type: 'keyword', - }, - params: taskManagerIndexMapping.params, - state: taskManagerIndexMapping.state, - runAt: taskManagerIndexMapping.runAt, - } as Record, - }, + mappings: { + properties: { + type: { + type: 'keyword', + }, + taskId: { + type: 'keyword', + }, + params: taskManagerIndexMapping.params, + state: taskManagerIndexMapping.state, + runAt: taskManagerIndexMapping.runAt, + } as Record, }, }); } @@ -151,7 +147,7 @@ export default function ({ getService }: FtrProviderContext) { await es.deleteByQuery({ index: '.kibana_task_manager', refresh: true, - body: { query: { terms: { id: [testNode1, testNode2] } } }, + query: { terms: { id: [testNode1, testNode2] } }, }); }); diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_priority.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_priority.ts index f8fc3f63987b9..be801955050c3 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_priority.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_priority.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server'; import { taskMappings as TaskManagerMapping } from '@kbn/task-manager-plugin/server/saved_objects/mappings'; import { asyncForEach } from '@kbn/std'; @@ -85,11 +85,9 @@ export default function ({ getService }: FtrProviderContext) { return es .search({ index: testHistoryIndex, - body: { - query: { - bool: { - filter, - }, + query: { + bool: { + filter, }, }, }) @@ -103,25 +101,23 @@ export default function ({ getService }: FtrProviderContext) { await es.deleteByQuery({ index: testHistoryIndex, refresh: true, - body: { query: { term: { type: 'task' } } }, + query: { term: { type: 'task' } }, }); } else { await es.indices.create({ index: testHistoryIndex, - body: { - mappings: { - properties: { - type: { - type: 'keyword', - }, - taskId: { - type: 'keyword', - }, - params: taskManagerIndexMapping.params, - state: taskManagerIndexMapping.state, - runAt: taskManagerIndexMapping.runAt, - } as Record, - }, + mappings: { + properties: { + type: { + type: 'keyword', + }, + taskId: { + type: 'keyword', + }, + params: taskManagerIndexMapping.params, + state: taskManagerIndexMapping.state, + runAt: taskManagerIndexMapping.runAt, + } as Record, }, }); } diff --git a/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2.ts b/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2.ts index 78403308dea91..47f6e487360b1 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2.ts @@ -68,21 +68,19 @@ export default ({ getService }: FtrProviderContext) => { log.info(`loading test data`); await es.indices.create({ index: timelessIndexName, - body: { - settings: { number_of_shards: 1 }, - mappings: { - properties: { - eon: { type: 'keyword' }, - era: { type: 'keyword' }, - period: { type: 'keyword' }, - epoch: { type: 'keyword' }, - }, + settings: { number_of_shards: 1 }, + mappings: { + properties: { + eon: { type: 'keyword' }, + era: { type: 'keyword' }, + period: { type: 'keyword' }, + epoch: { type: 'keyword' }, }, }, }); await es.bulk({ refresh: 'wait_for', - body: [ + operations: [ { index: { _index: timelessIndexName, _id: 'tvJJX4UBvD7uFsw9L2x4' } }, { eon: 'Phanerozoic', era: 'Cenozoic', period: 'Neogene', epoch: ' Pliocene' }, { index: { _index: timelessIndexName, _id: 't_JJX4UBvD7uFsw9L2x4' } }, diff --git a/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2_esql.ts b/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2_esql.ts index 0489bef799100..4948d46d4238f 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2_esql.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security/csv/csv_v2_esql.ts @@ -47,21 +47,19 @@ export default ({ getService }: FtrProviderContext) => { log.info(`loading test data`); await es.indices.create({ index: timelessIndexName, - body: { - settings: { number_of_shards: 1 }, - mappings: { - properties: { - eon: { type: 'keyword' }, - era: { type: 'keyword' }, - period: { type: 'keyword' }, - epoch: { type: 'keyword' }, - }, + settings: { number_of_shards: 1 }, + mappings: { + properties: { + eon: { type: 'keyword' }, + era: { type: 'keyword' }, + period: { type: 'keyword' }, + epoch: { type: 'keyword' }, }, }, }); await es.bulk({ refresh: 'wait_for', - body: [ + operations: [ { index: { _index: timelessIndexName, _id: 'tvJJX4UBvD7uFsw9L2x4' } }, { eon: 'Phanerozoic', era: 'Cenozoic', period: 'Neogene', epoch: ' Pliocene' }, { index: { _index: timelessIndexName, _id: 't_JJX4UBvD7uFsw9L2x4' } }, diff --git a/x-pack/test/reporting_api_integration/reporting_and_security/ilm_migration_apis.ts b/x-pack/test/reporting_api_integration/reporting_and_security/ilm_migration_apis.ts index 56009ccdd8b3d..70709ebf4f410 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security/ilm_migration_apis.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security/ilm_migration_apis.ts @@ -172,7 +172,7 @@ export default function ({ getService }: FtrProviderContext) { // customize the lifecycle policy await es.ilm.putLifecycle({ name: ILM_POLICY_NAME, - body: customLifecycle, + ...customLifecycle, }); await runMigrate(); diff --git a/x-pack/test/rule_registry/common/lib/helpers/create_apm_metric_index.ts b/x-pack/test/rule_registry/common/lib/helpers/create_apm_metric_index.ts index fab0f79d5a15f..b5877d75c4ca5 100644 --- a/x-pack/test/rule_registry/common/lib/helpers/create_apm_metric_index.ts +++ b/x-pack/test/rule_registry/common/lib/helpers/create_apm_metric_index.ts @@ -11,58 +11,56 @@ export const createApmMetricIndex = async (getService: GetService) => { const es = getService('es'); await es.indices.create({ index: APM_METRIC_INDEX_NAME, - body: { - mappings: { - dynamic: 'strict', - properties: { - event: { - properties: { - outcome: { - type: 'keyword', - }, + mappings: { + dynamic: 'strict', + properties: { + event: { + properties: { + outcome: { + type: 'keyword', }, }, - processor: { - properties: { - event: { - type: 'keyword', - }, + }, + processor: { + properties: { + event: { + type: 'keyword', }, }, - observer: { - properties: { - version_major: { - type: 'byte', - }, + }, + observer: { + properties: { + version_major: { + type: 'byte', }, }, - service: { - properties: { - name: { - type: 'keyword', - }, - environment: { - type: 'keyword', - }, + }, + service: { + properties: { + name: { + type: 'keyword', + }, + environment: { + type: 'keyword', }, }, - transaction: { - properties: { - type: { - type: 'keyword', - }, - duration: { - properties: { - histogram: { - type: 'histogram', - }, + }, + transaction: { + properties: { + type: { + type: 'keyword', + }, + duration: { + properties: { + histogram: { + type: 'histogram', }, }, }, }, - '@timestamp': { - type: 'date', - }, + }, + '@timestamp': { + type: 'date', }, }, }, diff --git a/x-pack/test/rule_registry/common/lib/helpers/delete_alert.ts b/x-pack/test/rule_registry/common/lib/helpers/delete_alert.ts index b373d0ffe8667..f7cf29a898c5a 100644 --- a/x-pack/test/rule_registry/common/lib/helpers/delete_alert.ts +++ b/x-pack/test/rule_registry/common/lib/helpers/delete_alert.ts @@ -35,10 +35,8 @@ export const deleteAlert = async ( await es.deleteByQuery({ index: targetIndices[0], - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, refresh: true, }); diff --git a/x-pack/test/saved_object_api_integration/common/lib/create_users_and_roles.ts b/x-pack/test/saved_object_api_integration/common/lib/create_users_and_roles.ts index eb7a729ff5c96..4c802b66e72fe 100644 --- a/x-pack/test/saved_object_api_integration/common/lib/create_users_and_roles.ts +++ b/x-pack/test/saved_object_api_integration/common/lib/create_users_and_roles.ts @@ -135,101 +135,81 @@ export const createUsersAndRoles = async (es: Client, supertest: SuperTestAgent) await es.security.putUser({ username: AUTHENTICATION.NOT_A_KIBANA_USER.username, - body: { - password: AUTHENTICATION.NOT_A_KIBANA_USER.password, - roles: [], - full_name: 'not a kibana user', - email: 'not_a_kibana_user@elastic.co', - }, + password: AUTHENTICATION.NOT_A_KIBANA_USER.password, + roles: [], + full_name: 'not a kibana user', + email: 'not_a_kibana_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_LEGACY_USER.username, - body: { - password: AUTHENTICATION.KIBANA_LEGACY_USER.password, - roles: ['kibana_legacy_user'], - full_name: 'a kibana legacy user', - email: 'a_kibana_legacy_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_LEGACY_USER.password, + roles: ['kibana_legacy_user'], + full_name: 'a kibana legacy user', + email: 'a_kibana_legacy_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_USER.username, - body: { - password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_USER.password, - roles: ['kibana_dual_privileges_user'], - full_name: 'a kibana dual_privileges user', - email: 'a_kibana_dual_privileges_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_USER.password, + roles: ['kibana_dual_privileges_user'], + full_name: 'a kibana dual_privileges user', + email: 'a_kibana_dual_privileges_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER.username, - body: { - password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER.password, - roles: ['kibana_dual_privileges_dashboard_only_user'], - full_name: 'a kibana dual_privileges dashboard only user', - email: 'a_kibana_dual_privileges_dashboard_only_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER.password, + roles: ['kibana_dual_privileges_dashboard_only_user'], + full_name: 'a kibana dual_privileges dashboard only user', + email: 'a_kibana_dual_privileges_dashboard_only_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_USER.password, - roles: ['kibana_rbac_user'], - full_name: 'a kibana user', - email: 'a_kibana_rbac_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_USER.password, + roles: ['kibana_rbac_user'], + full_name: 'a kibana user', + email: 'a_kibana_rbac_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DASHBOARD_ONLY_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DASHBOARD_ONLY_USER.password, - roles: ['kibana_rbac_dashboard_only_user'], - full_name: 'a kibana dashboard only user', - email: 'a_kibana_rbac_dashboard_only_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DASHBOARD_ONLY_USER.password, + roles: ['kibana_rbac_dashboard_only_user'], + full_name: 'a kibana dashboard only user', + email: 'a_kibana_rbac_dashboard_only_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_ALL_USER.password, - roles: ['kibana_rbac_default_space_all_user'], - full_name: 'a kibana default space all user', - email: 'a_kibana_rbac_default_space_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_ALL_USER.password, + roles: ['kibana_rbac_default_space_all_user'], + full_name: 'a kibana default space all user', + email: 'a_kibana_rbac_default_space_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_READ_USER.password, - roles: ['kibana_rbac_default_space_read_user'], - full_name: 'a kibana default space read-only user', - email: 'a_kibana_rbac_default_space_read_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_READ_USER.password, + roles: ['kibana_rbac_default_space_read_user'], + full_name: 'a kibana default space read-only user', + email: 'a_kibana_rbac_default_space_read_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_ALL_USER.password, - roles: ['kibana_rbac_space_1_all_user'], - full_name: 'a kibana rbac space 1 all user', - email: 'a_kibana_rbac_space_1_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_ALL_USER.password, + roles: ['kibana_rbac_space_1_all_user'], + full_name: 'a kibana rbac space 1 all user', + email: 'a_kibana_rbac_space_1_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_READ_USER.password, - roles: ['kibana_rbac_space_1_read_user'], - full_name: 'a kibana rbac space 1 read-only user', - email: 'a_kibana_rbac_space_1_readonly_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_READ_USER.password, + roles: ['kibana_rbac_space_1_read_user'], + full_name: 'a kibana rbac space 1 read-only user', + email: 'a_kibana_rbac_space_1_readonly_user@elastic.co', }); }; diff --git a/x-pack/test/saved_object_api_integration/common/suites/bulk_delete.ts b/x-pack/test/saved_object_api_integration/common/suites/bulk_delete.ts index f7fe4ba4061ce..4df8b9cd50215 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/bulk_delete.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/bulk_delete.ts @@ -73,11 +73,9 @@ export function bulkDeleteTestSuiteFactory(context: FtrProviderContext) { await es.indices.refresh({ index: '.kibana' }); // alias deletion uses refresh: false, so we need to manually refresh the index before searching const searchResponse = await es.search({ index: '.kibana', - body: { - size: 0, - query: { terms: { type: ['legacy-url-alias'] } }, - track_total_hits: true, - }, + size: 0, + query: { terms: { type: ['legacy-url-alias'] } }, + track_total_hits: true, }); const expectAliasWasDeleted = !![ALIAS_DELETE_INCLUSIVE, ALIAS_DELETE_EXCLUSIVE].find( diff --git a/x-pack/test/saved_object_api_integration/common/suites/delete.ts b/x-pack/test/saved_object_api_integration/common/suites/delete.ts index 032c19cd0f8ae..c24a816d06bc3 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/delete.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/delete.ts @@ -58,11 +58,9 @@ export function deleteTestSuiteFactory(es: Client, esArchiver: any, supertest: S await es.indices.refresh({ index: '.kibana' }); // alias deletion uses refresh: false, so we need to manually refresh the index before searching const searchResponse = await es.search({ index: '.kibana', - body: { - size: 0, - query: { terms: { type: ['legacy-url-alias'] } }, - track_total_hits: true, - }, + size: 0, + query: { terms: { type: ['legacy-url-alias'] } }, + track_total_hits: true, }); const expectAliasWasDeleted = !![ALIAS_DELETE_INCLUSIVE, ALIAS_DELETE_EXCLUSIVE].find( ({ type, id }) => testCase.type === type && testCase.id === id diff --git a/x-pack/test/screenshot_creation/apps/ml_docs/anomaly_detection/generate_anomaly_alerts.ts b/x-pack/test/screenshot_creation/apps/ml_docs/anomaly_detection/generate_anomaly_alerts.ts index 75c441bc21cd9..a53ff9447925c 100644 --- a/x-pack/test/screenshot_creation/apps/ml_docs/anomaly_detection/generate_anomaly_alerts.ts +++ b/x-pack/test/screenshot_creation/apps/ml_docs/anomaly_detection/generate_anomaly_alerts.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DATAFEED_STATE } from '@kbn/ml-plugin/common/constants/states'; import { FtrProviderContext } from '../../../ftr_provider_context'; diff --git a/x-pack/test/screenshot_creation/apps/response_ops_docs/stack_connectors/index.ts b/x-pack/test/screenshot_creation/apps/response_ops_docs/stack_connectors/index.ts index 05084e9f72b90..403b72f2a2c78 100644 --- a/x-pack/test/screenshot_creation/apps/response_ops_docs/stack_connectors/index.ts +++ b/x-pack/test/screenshot_creation/apps/response_ops_docs/stack_connectors/index.ts @@ -26,13 +26,11 @@ export default function ({ loadTestFile, getService }: FtrProviderContext) { await es.indices.create({ index: testIndex, - body: { - mappings: { - properties: { - date_updated: { - type: 'date', - format: 'epoch_millis', - }, + mappings: { + properties: { + date_updated: { + type: 'date', + format: 'epoch_millis', }, }, }, diff --git a/x-pack/test/security_api_integration/tests/api_keys/has_active_key.ts b/x-pack/test/security_api_integration/tests/api_keys/has_active_key.ts index 6a6c98271a888..573d203a561a0 100644 --- a/x-pack/test/security_api_integration/tests/api_keys/has_active_key.ts +++ b/x-pack/test/security_api_integration/tests/api_keys/has_active_key.ts @@ -25,7 +25,7 @@ export default function ({ getService }: FtrProviderContext) { const cleanup = async () => { await getService('es').deleteByQuery({ index: '.security-7', - body: { query: { match: { doc_type: 'api_key' } } }, + query: { match: { doc_type: 'api_key' } }, refresh: true, }); }; diff --git a/x-pack/test/security_api_integration/tests/http_bearer/access_token.ts b/x-pack/test/security_api_integration/tests/http_bearer/access_token.ts index 26a70bb286a1f..ae674dc0cf346 100644 --- a/x-pack/test/security_api_integration/tests/http_bearer/access_token.ts +++ b/x-pack/test/security_api_integration/tests/http_bearer/access_token.ts @@ -16,10 +16,8 @@ export default function ({ getService }: FtrProviderContext) { async function createToken() { const { access_token: accessToken, authentication } = await es.security.getToken({ - body: { - grant_type: 'password', - ...adminTestUser, - }, + grant_type: 'password', + ...adminTestUser, }); return { @@ -75,7 +73,7 @@ export default function ({ getService }: FtrProviderContext) { it('rejects invalidated access token via authorization Bearer header', async () => { const { accessToken } = await createToken(); - await es.security.invalidateToken({ body: { token: accessToken } }); + await es.security.invalidateToken({ token: accessToken }); await supertest .get('/internal/security/me') diff --git a/x-pack/test/security_api_integration/tests/http_bearer/jwt.ts b/x-pack/test/security_api_integration/tests/http_bearer/jwt.ts index 2ccfdeec77cb5..7a4f09ad1bc7b 100644 --- a/x-pack/test/security_api_integration/tests/http_bearer/jwt.ts +++ b/x-pack/test/security_api_integration/tests/http_bearer/jwt.ts @@ -61,7 +61,8 @@ export default function ({ getService }: FtrProviderContext) { assertUser(user, 'elastic-agent-no-secret'); const { access_token: accessToken } = await es.security.getToken({ - body: { grant_type: 'password', ...adminTestUser }, + grant_type: 'password', + ...adminTestUser, }); const { body: accessTokenUser } = await supertest .get('/internal/security/me') diff --git a/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts b/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts index edfc037c936fe..8574ede3cd835 100644 --- a/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts +++ b/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts @@ -457,7 +457,7 @@ export default function ({ getService }: FtrProviderContext) { // some period of time. const esResponse = await getService('es').deleteByQuery({ index: '.security-tokens', - body: { query: { match: { doc_type: 'token' } } }, + query: { match: { doc_type: 'token' } }, refresh: true, }); expect(esResponse).to.have.property('deleted').greaterThan(0); diff --git a/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts b/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts index c14379ce753af..d21b712e1e2fd 100644 --- a/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts +++ b/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts @@ -632,7 +632,7 @@ export default function ({ getService }: FtrProviderContext) { // after some period of time. const esResponse = await getService('es').deleteByQuery({ index: '.security-tokens', - body: { query: { match: { doc_type: 'token' } } }, + query: { match: { doc_type: 'token' } }, refresh: true, }); expect(esResponse).to.have.property('deleted').greaterThan(0); diff --git a/x-pack/test/security_api_integration/tests/saml/saml_login.ts b/x-pack/test/security_api_integration/tests/saml/saml_login.ts index 71994bc5512ca..e9a8c23e1763a 100644 --- a/x-pack/test/security_api_integration/tests/saml/saml_login.ts +++ b/x-pack/test/security_api_integration/tests/saml/saml_login.ts @@ -626,7 +626,7 @@ export default function ({ getService }: FtrProviderContext) { // after some period of time. const esResponse = await getService('es').deleteByQuery({ index: '.security-tokens', - body: { query: { match: { doc_type: 'token' } } }, + query: { match: { doc_type: 'token' } }, refresh: true, }); expect(esResponse).to.have.property('deleted').greaterThan(0); @@ -711,7 +711,7 @@ export default function ({ getService }: FtrProviderContext) { const esResponse = await getService('es').deleteByQuery({ index: '.security-tokens', - body: { query: { match: { doc_type: 'token' } } }, + query: { match: { doc_type: 'token' } }, refresh: true, }); expect(esResponse).to.have.property('deleted').greaterThan(0); diff --git a/x-pack/test/security_api_integration/tests/session_concurrent_limit/cleanup.ts b/x-pack/test/security_api_integration/tests/session_concurrent_limit/cleanup.ts index cac4f3b678149..f672062f0268e 100644 --- a/x-pack/test/security_api_integration/tests/session_concurrent_limit/cleanup.ts +++ b/x-pack/test/security_api_integration/tests/session_concurrent_limit/cleanup.ts @@ -333,7 +333,8 @@ export default function ({ getService }: FtrProviderContext) { // 3. Remove `createdAt` field for the latest sessions emulating legacy sessions. await es.updateByQuery({ index: '.kibana_security_session*', - body: { script: 'ctx._source.remove("createdAt")', query: { ids: { values: sessionIds } } }, + script: 'ctx._source.remove("createdAt")', + query: { ids: { values: sessionIds } }, refresh: true, }); diff --git a/x-pack/test/security_api_integration/tests/token/header.ts b/x-pack/test/security_api_integration/tests/token/header.ts index 304d2f4b0e4dd..e0d8b69d06c11 100644 --- a/x-pack/test/security_api_integration/tests/token/header.ts +++ b/x-pack/test/security_api_integration/tests/token/header.ts @@ -13,11 +13,9 @@ export default function ({ getService }: FtrProviderContext) { async function createToken() { const { access_token: accessToken } = await es.security.getToken({ - body: { - grant_type: 'password', - username: 'elastic', - password: 'changeme', - }, + grant_type: 'password', + username: 'elastic', + password: 'changeme', }); return accessToken; diff --git a/x-pack/test/security_api_integration/tests/token/session.ts b/x-pack/test/security_api_integration/tests/token/session.ts index 1e90f278ea594..c0dfe7010df4d 100644 --- a/x-pack/test/security_api_integration/tests/token/session.ts +++ b/x-pack/test/security_api_integration/tests/token/session.ts @@ -200,7 +200,7 @@ export default function ({ getService }: FtrProviderContext) { // after some period of time. const esResponse = await getService('es').deleteByQuery({ index: '.security-tokens', - body: { query: { match: { doc_type: 'token' } } }, + query: { match: { doc_type: 'token' } }, refresh: true, }); expect(esResponse).to.have.property('deleted').greaterThan(0); diff --git a/x-pack/test/security_functional/tests/insecure_cluster_warning/insecure_cluster_warning.ts b/x-pack/test/security_functional/tests/insecure_cluster_warning/insecure_cluster_warning.ts index 9306b290a0ec1..b44b46e9a2542 100644 --- a/x-pack/test/security_functional/tests/insecure_cluster_warning/insecure_cluster_warning.ts +++ b/x-pack/test/security_functional/tests/insecure_cluster_warning/insecure_cluster_warning.ts @@ -20,7 +20,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { this.tags('skipFIPS'); before(async () => { await es.indices.create({ index: 'my-index-001' }); - await es.index({ index: 'my-index-001', body: { foo: 'bar' } }); + await es.index({ index: 'my-index-001', document: { foo: 'bar' } }); }); after(async () => { diff --git a/x-pack/test/security_solution_api_integration/config/services/security_solution_edr_workflows_resolver.ts b/x-pack/test/security_solution_api_integration/config/services/security_solution_edr_workflows_resolver.ts index b9eed4dec9fae..b555b6dd88a3e 100644 --- a/x-pack/test/security_solution_api_integration/config/services/security_solution_edr_workflows_resolver.ts +++ b/x-pack/test/security_solution_api_integration/config/services/security_solution_edr_workflows_resolver.ts @@ -57,11 +57,11 @@ export function ResolverGeneratorProvider({ getService }: FtrProviderContext) { events: Event[], eventsIndex: string = processEventsIndex ): Promise { - const body = events.reduce((array: Array, doc) => { + const operations = events.reduce((array: Array, doc) => { array.push({ create: { _index: eventsIndex } }, doc); return array; }, []); - const bulkResp = await client.bulk({ body, refresh: true }); + const bulkResp = await client.bulk({ operations, refresh: true }); const eventsInfo = events.map((event: Event, i: number) => { return { event, _id: bulkResp.items[i].create?._id }; @@ -81,7 +81,7 @@ export function ResolverGeneratorProvider({ getService }: FtrProviderContext) { const numTrees = options.numTrees ?? 1; for (let j = 0; j < numTrees; j++) { const tree = generator.generateTree(options); - const body = tree.allEvents.reduce((array: Array, doc) => { + const operations = tree.allEvents.reduce((array: Array, doc) => { let index = eventsIndex; if (firstNonNullValue(doc.event?.kind) === 'alert') { index = alertsIndex; @@ -93,7 +93,7 @@ export function ResolverGeneratorProvider({ getService }: FtrProviderContext) { return array; }, []); // force a refresh here otherwise the documents might not be available when the tests search for them - await client.bulk({ body, refresh: true }); + await client.bulk({ operations, refresh: true }); allTrees.push(tree); } return { trees: allTrees, indices: [eventsIndex, alertsIndex] }; diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status.ts index 888810e914a3d..2d5232124058d 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { ALERT_WORKFLOW_STATUS } from '@kbn/rule-data-utils'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DETECTION_ENGINE_SIGNALS_STATUS_URL, diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status_ess.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status_ess.ts index 9541badc5e6de..e8ec236eab5cf 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status_ess.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/alert_status/alert_status_ess.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { parse as parseCookie } from 'tough-cookie'; import { adminTestUser } from '@kbn/test'; diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/ess_specific_index_logic/alerts_compatibility.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/ess_specific_index_logic/alerts_compatibility.ts index d98afe99addc7..060ea925b85f9 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/ess_specific_index_logic/alerts_compatibility.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/ess_specific_index_logic/alerts_compatibility.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import expect from '@kbn/expect'; import { diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/set_alert_tags.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/set_alert_tags.ts index f3a0206a58abf..dec8bf7231e9c 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/set_alert_tags.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/basic_license_essentials_tier/set_alert_tags.ts @@ -6,7 +6,7 @@ */ import expect from 'expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DETECTION_ENGINE_QUERY_SIGNALS_URL, diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/trial_license_complete_tier/assignments/assignments.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/trial_license_complete_tier/assignments/assignments.ts index 436ebc469c25e..6dd4ef213a1b9 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/trial_license_complete_tier/assignments/assignments.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/detection_engine/alerts/trial_license_complete_tier/assignments/assignments.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { DETECTION_ENGINE_ALERT_ASSIGNEES_URL, diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/downgrade_immutable_rule.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/downgrade_immutable_rule.ts index fc81e2fc30cb4..242711be7faa5 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/downgrade_immutable_rule.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/downgrade_immutable_rule.ts @@ -22,15 +22,13 @@ export const downgradeImmutableRule = async ( index: ALERTING_CASES_SAVED_OBJECT_INDEX, refresh: true, wait_for_completion: true, - body: { - script: { - lang: 'painless', - source: 'ctx._source.alert.params.version--', - }, - query: { - term: { - 'alert.params.ruleId': ruleId, - }, + script: { + lang: 'painless', + source: 'ctx._source.alert.params.version--', + }, + query: { + term: { + 'alert.params.ruleId': ruleId, }, }, }, diff --git a/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/prebuilt_rules/create_prebuilt_rule_saved_objects.ts b/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/prebuilt_rules/create_prebuilt_rule_saved_objects.ts index 8780bf2b49353..256dd76147b24 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/prebuilt_rules/create_prebuilt_rule_saved_objects.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/detections_response/utils/rules/prebuilt_rules/create_prebuilt_rule_saved_objects.ts @@ -90,7 +90,7 @@ export const createPrebuiltRuleAssetSavedObjects = async ( ): Promise => { await es.bulk({ refresh: true, - body: rules.flatMap((doc) => [ + operations: rules.flatMap((doc) => [ { index: { _index: SECURITY_SOLUTION_SAVED_OBJECT_INDEX, @@ -117,7 +117,7 @@ export const createHistoricalPrebuiltRuleAssetSavedObjects = async ( ): Promise => { const response = await es.bulk({ refresh: true, - body: rules.flatMap((doc) => [ + operations: rules.flatMap((doc) => [ { index: { _index: SECURITY_SOLUTION_SAVED_OBJECT_INDEX, diff --git a/x-pack/test/security_solution_api_integration/test_suites/edr_workflows/package/trial_license_complete_tier/package.ts b/x-pack/test/security_solution_api_integration/test_suites/edr_workflows/package/trial_license_complete_tier/package.ts index 11beabd6edd25..60ce6d6f55a1b 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/edr_workflows/package/trial_license_complete_tier/package.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/edr_workflows/package/trial_license_complete_tier/package.ts @@ -54,17 +54,15 @@ export default function ({ getService }: FtrProviderContext) { return es.search( { index: eventsIndexPattern, - body: { - query: { - bool: { - filter: [ - { - ids: { - values: [id], - }, + query: { + bool: { + filter: [ + { + ids: { + values: [id], }, - ], - }, + }, + ], }, }, }, diff --git a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/entity_store/utils/ingest.ts b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/entity_store/utils/ingest.ts index e934281fcea3b..cfc5eabebe5ab 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/entity_store/utils/ingest.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/entity_store/utils/ingest.ts @@ -6,7 +6,7 @@ */ import { Client } from '@elastic/elasticsearch'; -import { IngestProcessorContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { IngestProcessorContainer } from '@elastic/elasticsearch/lib/api/types'; import { ToolingLog } from '@kbn/tooling-log'; export const applyIngestProcessorToDoc = async ( diff --git a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/risk_engine/trial_license_complete_tier/init_and_status_apis.ts b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/risk_engine/trial_license_complete_tier/init_and_status_apis.ts index 1d7175a4c3384..aef4b252a3cb8 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/risk_engine/trial_license_complete_tier/init_and_status_apis.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/risk_engine/trial_license_complete_tier/init_and_status_apis.ts @@ -676,57 +676,53 @@ export default ({ getService }: FtrProviderContext) => { await es.cluster.putComponentTemplate({ name: componentTemplateName, - body: { - template: { - settings: { - number_of_shards: 1, - }, - mappings: { - properties: { - timestamp: { - type: 'date', - }, - user: { - properties: { - id: { - type: 'keyword', - }, - name: { - type: 'text', - }, + template: { + settings: { + number_of_shards: 1, + }, + mappings: { + properties: { + timestamp: { + type: 'date', + }, + user: { + properties: { + id: { + type: 'keyword', + }, + name: { + type: 'text', }, }, }, }, }, - version: 1, }, + version: 1, }); // Call an API to put the index template await es.indices.putIndexTemplate({ name: indexTemplateName, - body: { - index_patterns: [indexTemplateName], - composed_of: [componentTemplateName], - template: { - settings: { - number_of_shards: 1, - }, - mappings: { - properties: { - timestamp: { - type: 'date', - }, - user: { - properties: { - id: { - type: 'keyword', - }, - name: { - type: 'text', - }, + index_patterns: [indexTemplateName], + composed_of: [componentTemplateName], + template: { + settings: { + number_of_shards: 1, + }, + mappings: { + properties: { + timestamp: { + type: 'date', + }, + user: { + properties: { + id: { + type: 'keyword', + }, + name: { + type: 'text', }, }, }, diff --git a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/asset_criticality.ts b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/asset_criticality.ts index 690e8f99b4611..ee5f5be07871e 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/asset_criticality.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/asset_criticality.ts @@ -199,7 +199,7 @@ export const createAssetCriticalityRecords = async ( records: CreateAssetCriticalityRecord[], es: Client ) => { - const ops = records.flatMap((record) => [ + const operations = records.flatMap((record) => [ { index: { _index: getAssetCriticalityIndex(), @@ -210,7 +210,7 @@ export const createAssetCriticalityRecords = async ( ]); const res = await es.bulk({ - body: ops, + operations, refresh: 'wait_for', }); diff --git a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/risk_engine.ts b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/risk_engine.ts index 232b89fa492c7..ba609a0508fcf 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/risk_engine.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/entity_analytics/utils/risk_engine.ts @@ -188,10 +188,8 @@ export const deleteAllRiskScores = async ( async () => { await es.deleteByQuery({ index, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, ignore_unavailable: true, refresh: true, diff --git a/x-pack/test/security_solution_api_integration/test_suites/lists_and_exception_lists/utils.ts b/x-pack/test/security_solution_api_integration/test_suites/lists_and_exception_lists/utils.ts index e4311a375f657..0359a6c607cbe 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/lists_and_exception_lists/utils.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/lists_and_exception_lists/utils.ts @@ -594,7 +594,7 @@ export const createListsIndices = async (es: Client) => { */ export const createListBypassingChecks = async ({ es, id }: { es: Client; id: string }) => { const createdAt = new Date().toISOString(); - const body = { + const document = { created_at: createdAt, created_by: 'mock-user', description: 'mock-description', @@ -608,7 +608,7 @@ export const createListBypassingChecks = async ({ es, id }: { es: Client; id: st }; const response = await es.create({ - body, + document, id, index: '.lists-default', refresh: 'wait_for', @@ -617,7 +617,7 @@ export const createListBypassingChecks = async ({ es, id }: { es: Client; id: st return { _version: encodeHitVersion(response), id: response._id, - ...body, + ...document, }; }; @@ -638,7 +638,7 @@ export const createListItemBypassingChecks = async ({ value: string; }) => { const createdAt = new Date().toISOString(); - const body = { + const document = { created_at: createdAt, created_by: 'mock-user', tie_breaker_id: uuidv4(), @@ -649,7 +649,7 @@ export const createListItemBypassingChecks = async ({ }; const response = await es.create({ - body, + document, id, index: '.items-default', refresh: 'wait_for', @@ -658,7 +658,7 @@ export const createListItemBypassingChecks = async ({ return { _version: encodeHitVersion(response), id: response._id, - ...body, + ...document, }; }; @@ -718,13 +718,11 @@ const createReindexedBootstrapIndex = async (esClient: Client, index: string): P await esClient.indices.create( { index: `.reindexed-v8-${index}-000001`, - body: { - aliases: { - [`.${index}`]: { - is_write_index: true, - }, - [`.${index}-000001`]: {}, + aliases: { + [`.${index}`]: { + is_write_index: true, }, + [`.${index}-000001`]: {}, }, }, { meta: true } diff --git a/x-pack/test/security_solution_api_integration/test_suites/siem_migrations/utils/mocks.ts b/x-pack/test/security_solution_api_integration/test_suites/siem_migrations/utils/mocks.ts index 184e19f8d0c9c..90abdac6a27e4 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/siem_migrations/utils/mocks.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/siem_migrations/utils/mocks.ts @@ -179,10 +179,8 @@ export const createMigrationRules = async ( export const deleteAllMigrationRules = async (es: Client): Promise => { await es.deleteByQuery({ index: [SIEM_MIGRATIONS_RULES_INDEX_PATTERN], - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, ignore_unavailable: true, refresh: true, diff --git a/x-pack/test/security_solution_api_integration/test_suites/utils.ts b/x-pack/test/security_solution_api_integration/test_suites/utils.ts index c4ce2e852c26a..716a2cb30c099 100644 --- a/x-pack/test/security_solution_api_integration/test_suites/utils.ts +++ b/x-pack/test/security_solution_api_integration/test_suites/utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportResult } from '@elastic/elasticsearch'; import type { Client } from '@elastic/elasticsearch'; import { JsonObject } from '@kbn/utility-types'; @@ -19,20 +19,18 @@ export async function getSavedObjectFromES( return await es.search( { index: ALL_SAVED_OBJECT_INDICES, - body: { - query: { - bool: { - filter: [ - { ...query }, - { - term: { - type: { - value: savedObjectType, - }, + query: { + bool: { + filter: [ + { ...query }, + { + term: { + type: { + value: savedObjectType, }, }, - ], - }, + }, + ], }, }, }, diff --git a/x-pack/test/security_solution_cypress/cypress/support/es_client.ts b/x-pack/test/security_solution_cypress/cypress/support/es_client.ts index 4b5e114ed33dd..994f9ffab7a29 100644 --- a/x-pack/test/security_solution_cypress/cypress/support/es_client.ts +++ b/x-pack/test/security_solution_cypress/cypress/support/es_client.ts @@ -22,7 +22,7 @@ export const esClient = ( /* system_indices_superuser is a user created for testing purposes (an operator one) that does not have restrictions, - that user is the one used on ESS and stateless environments to access internal indexes directly and does not exist on MKI environments. + that user is the one used on ESS and stateless environments to access internal indexes directly and does not exist on MKI environments. */ const authOverride = isServerless ? (isCloudServerless ? user : systemIndicesSuperuser) : user; @@ -36,16 +36,14 @@ export const esClient = ( putMapping: async (index: string) => { await client.indices.putMapping({ index, - body: { - dynamic: true, - }, + dynamic: true, }); return null; }, - bulkInsert: async (body) => { + bulkInsert: async (operations) => { await client.bulk({ refresh: true, - body, + operations, }); return null; }, @@ -61,10 +59,8 @@ export const esClient = ( try { const response = await client.search({ index, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, }); @@ -98,10 +94,8 @@ export const esClient = ( deleteDocuments: async (index: string) => { await client.deleteByQuery({ index, - body: { - query: { - match_all: {}, - }, + query: { + match_all: {}, }, conflicts: 'proceed', scroll_size: 10000, @@ -112,10 +106,8 @@ export const esClient = ( createIndex: async ({ index: indexName, properties }) => { const result = await client.indices.create({ index: indexName, - body: { - mappings: { - properties, - }, + mappings: { + properties, }, }); return result; @@ -132,17 +124,15 @@ export const esClient = ( deleteSecurityRulesFromKibana: async () => { await client.deleteByQuery({ index: '.kibana_*', - body: { - query: { - bool: { - filter: [ - { - match: { - type: 'security-rule', - }, + query: { + bool: { + filter: [ + { + match: { + type: 'security-rule', }, - ], - }, + }, + ], }, }, conflicts: 'proceed', diff --git a/x-pack/test/security_solution_ftr/services/detections/index.ts b/x-pack/test/security_solution_ftr/services/detections/index.ts index bc7c8855796ac..1adac97b65c28 100644 --- a/x-pack/test/security_solution_ftr/services/detections/index.ts +++ b/x-pack/test/security_solution_ftr/services/detections/index.ts @@ -12,7 +12,7 @@ import { DETECTION_ENGINE_RULES_BULK_ACTION, DETECTION_ENGINE_RULES_URL, } from '@kbn/security-solution-plugin/common/constants'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; import { Rule } from '@kbn/security-solution-plugin/public/detection_engine/rule_management/logic/types'; import { IndexedEndpointRuleAlerts, diff --git a/x-pack/test/spaces_api_integration/common/lib/create_users_and_roles.ts b/x-pack/test/spaces_api_integration/common/lib/create_users_and_roles.ts index f917a6efed15f..be5c3f644487f 100644 --- a/x-pack/test/spaces_api_integration/common/lib/create_users_and_roles.ts +++ b/x-pack/test/spaces_api_integration/common/lib/create_users_and_roles.ts @@ -271,231 +271,185 @@ export const createUsersAndRoles = async (es: Client, supertest: SuperTestAgent) await es.security.putUser({ username: AUTHENTICATION.NOT_A_KIBANA_USER.username, - body: { - password: AUTHENTICATION.NOT_A_KIBANA_USER.password, - roles: [], - full_name: 'not a kibana user', - email: 'not_a_kibana_user@elastic.co', - }, + password: AUTHENTICATION.NOT_A_KIBANA_USER.password, + roles: [], + full_name: 'not a kibana user', + email: 'not_a_kibana_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_LEGACY_USER.username, - body: { - password: AUTHENTICATION.KIBANA_LEGACY_USER.password, - roles: ['kibana_legacy_user'], - full_name: 'a kibana legacy user', - email: 'a_kibana_legacy_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_LEGACY_USER.password, + roles: ['kibana_legacy_user'], + full_name: 'a kibana legacy user', + email: 'a_kibana_legacy_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_USER.username, - body: { - password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_USER.password, - roles: ['kibana_dual_privileges_user'], - full_name: 'a kibana dual_privileges user', - email: 'a_kibana_dual_privileges_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_USER.password, + roles: ['kibana_dual_privileges_user'], + full_name: 'a kibana dual_privileges user', + email: 'a_kibana_dual_privileges_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER.username, - body: { - password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER.password, - roles: ['kibana_dual_privileges_dashboard_only_user'], - full_name: 'a kibana dual_privileges dashboard only user', - email: 'a_kibana_dual_privileges_dashboard_only_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER.password, + roles: ['kibana_dual_privileges_dashboard_only_user'], + full_name: 'a kibana dual_privileges dashboard only user', + email: 'a_kibana_dual_privileges_dashboard_only_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_USER.password, - roles: ['kibana_rbac_user'], - full_name: 'a kibana user', - email: 'a_kibana_rbac_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_USER.password, + roles: ['kibana_rbac_user'], + full_name: 'a kibana user', + email: 'a_kibana_rbac_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DASHBOARD_ONLY_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DASHBOARD_ONLY_USER.password, - roles: ['kibana_rbac_dashboard_only_user'], - full_name: 'a kibana dashboard only user', - email: 'a_kibana_rbac_dashboard_only_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DASHBOARD_ONLY_USER.password, + roles: ['kibana_rbac_dashboard_only_user'], + full_name: 'a kibana dashboard only user', + email: 'a_kibana_rbac_dashboard_only_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_ALL_USER.password, - roles: ['kibana_rbac_default_space_all_user'], - full_name: 'a kibana default space all user', - email: 'a_kibana_rbac_default_space_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_ALL_USER.password, + roles: ['kibana_rbac_default_space_all_user'], + full_name: 'a kibana default space all user', + email: 'a_kibana_rbac_default_space_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_READ_USER.password, - roles: ['kibana_rbac_default_space_read_user'], - full_name: 'a kibana default space read-only user', - email: 'a_kibana_rbac_default_space_read_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_READ_USER.password, + roles: ['kibana_rbac_default_space_read_user'], + full_name: 'a kibana default space read-only user', + email: 'a_kibana_rbac_default_space_read_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_ALL_USER.password, - roles: ['kibana_rbac_space_1_all_user'], - full_name: 'a kibana rbac space 1 all user', - email: 'a_kibana_rbac_space_1_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_ALL_USER.password, + roles: ['kibana_rbac_space_1_all_user'], + full_name: 'a kibana rbac space 1 all user', + email: 'a_kibana_rbac_space_1_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_READ_USER.password, - roles: ['kibana_rbac_space_1_read_user'], - full_name: 'a kibana rbac space 1 read-only user', - email: 'a_kibana_rbac_space_1_readonly_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_READ_USER.password, + roles: ['kibana_rbac_space_1_read_user'], + full_name: 'a kibana rbac space 1 read-only user', + email: 'a_kibana_rbac_space_1_readonly_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_3_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_3_ALL_USER.password, - roles: ['kibana_rbac_space_3_all_user'], - full_name: 'a kibana rbac space 3 all user', - email: 'a_kibana_rbac_space_3_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_3_ALL_USER.password, + roles: ['kibana_rbac_space_3_all_user'], + full_name: 'a kibana rbac space 3 all user', + email: 'a_kibana_rbac_space_3_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_3_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_3_READ_USER.password, - roles: ['kibana_rbac_space_3_read_user'], - full_name: 'a kibana rbac space 3 read-only user', - email: 'a_kibana_rbac_space_3_readonly_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_3_READ_USER.password, + roles: ['kibana_rbac_space_3_read_user'], + full_name: 'a kibana rbac space 3 read-only user', + email: 'a_kibana_rbac_space_3_readonly_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_2_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_2_ALL_USER.password, - roles: ['kibana_rbac_space_2_all_user'], - full_name: 'a kibana rbac space 2 all user', - email: 'a_kibana_rbac_space_2_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_2_ALL_USER.password, + roles: ['kibana_rbac_space_2_all_user'], + full_name: 'a kibana rbac space 2 all user', + email: 'a_kibana_rbac_space_2_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_2_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_2_READ_USER.password, - roles: ['kibana_rbac_space_2_read_user'], - full_name: 'a kibana rbac space 2 read-only user', - email: 'a_kibana_rbac_space_2_readonly_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_2_READ_USER.password, + roles: ['kibana_rbac_space_2_read_user'], + full_name: 'a kibana rbac space 2 read-only user', + email: 'a_kibana_rbac_space_2_readonly_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_2_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_2_ALL_USER.password, - roles: ['kibana_rbac_space_1_2_all_user'], - full_name: 'a kibana rbac space 1 and 2 all user', - email: 'a_kibana_rbac_space_1_2_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_2_ALL_USER.password, + roles: ['kibana_rbac_space_1_2_all_user'], + full_name: 'a kibana rbac space 1 and 2 all user', + email: 'a_kibana_rbac_space_1_2_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_2_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_2_READ_USER.password, - roles: ['kibana_rbac_space_1_2_read_user'], - full_name: 'a kibana rbac space 1 and 2 read-only user', - email: 'a_kibana_rbac_space_1_2_readonly_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_2_READ_USER.password, + roles: ['kibana_rbac_space_1_2_read_user'], + full_name: 'a kibana rbac space 1 and 2 read-only user', + email: 'a_kibana_rbac_space_1_2_readonly_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_SAVED_OBJECTS_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_SAVED_OBJECTS_ALL_USER.password, - roles: ['kibana_rbac_default_space_saved_objects_all_user'], - full_name: 'a kibana rbac default space saved objects management all user', - email: 'a_kibana_rbac_default_space_saved_objects_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_SAVED_OBJECTS_ALL_USER.password, + roles: ['kibana_rbac_default_space_saved_objects_all_user'], + full_name: 'a kibana rbac default space saved objects management all user', + email: 'a_kibana_rbac_default_space_saved_objects_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_SAVED_OBJECTS_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_SAVED_OBJECTS_READ_USER.password, - roles: ['kibana_rbac_default_space_saved_objects_read_user'], - full_name: 'a kibana rbac default space saved objects management read user', - email: 'a_kibana_rbac_default_space_saved_objects_read_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_DEFAULT_SPACE_SAVED_OBJECTS_READ_USER.password, + roles: ['kibana_rbac_default_space_saved_objects_read_user'], + full_name: 'a kibana rbac default space saved objects management read user', + email: 'a_kibana_rbac_default_space_saved_objects_read_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_SAVED_OBJECTS_ALL_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_SAVED_OBJECTS_ALL_USER.password, - roles: ['kibana_rbac_space_1_saved_objects_all_user'], - full_name: 'a kibana rbac space 1 saved objects management all user', - email: 'a_kibana_rbac_space_1_saved_objects_all_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_SAVED_OBJECTS_ALL_USER.password, + roles: ['kibana_rbac_space_1_saved_objects_all_user'], + full_name: 'a kibana rbac space 1 saved objects management all user', + email: 'a_kibana_rbac_space_1_saved_objects_all_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.KIBANA_RBAC_SPACE_1_SAVED_OBJECTS_READ_USER.username, - body: { - password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_SAVED_OBJECTS_READ_USER.password, - roles: ['kibana_rbac_space_1_saved_objects_read_user'], - full_name: 'a kibana rbac space 1 saved objects management read user', - email: 'a_kibana_rbac_space_1_saved_objects_read_user@elastic.co', - }, + password: AUTHENTICATION.KIBANA_RBAC_SPACE_1_SAVED_OBJECTS_READ_USER.password, + roles: ['kibana_rbac_space_1_saved_objects_read_user'], + full_name: 'a kibana rbac space 1 saved objects management read user', + email: 'a_kibana_rbac_space_1_saved_objects_read_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.MACHINE_LEARING_ADMIN.username, - body: { - password: AUTHENTICATION.MACHINE_LEARING_ADMIN.password, - roles: ['machine_learning_admin'], - full_name: 'a machine learning admin', - email: 'a_machine_learning_admin@elastic.co', - }, + password: AUTHENTICATION.MACHINE_LEARING_ADMIN.password, + roles: ['machine_learning_admin'], + full_name: 'a machine learning admin', + email: 'a_machine_learning_admin@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.MACHINE_LEARNING_USER.username, - body: { - password: AUTHENTICATION.MACHINE_LEARNING_USER.password, - roles: ['machine_learning_user'], - full_name: 'a machine learning user', - email: 'a_machine_learning_user@elastic.co', - }, + password: AUTHENTICATION.MACHINE_LEARNING_USER.password, + roles: ['machine_learning_user'], + full_name: 'a machine learning user', + email: 'a_machine_learning_user@elastic.co', }); await es.security.putUser({ username: AUTHENTICATION.MONITORING_USER.username, - body: { - password: AUTHENTICATION.MONITORING_USER.password, - roles: ['monitoring_user'], - full_name: 'a monitoring user', - email: 'a_monitoring_user@elastic.co', - }, + password: AUTHENTICATION.MONITORING_USER.password, + roles: ['monitoring_user'], + full_name: 'a monitoring user', + email: 'a_monitoring_user@elastic.co', }); }; diff --git a/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts b/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts index 70a597141f1c2..99fdbddead9f7 100644 --- a/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts +++ b/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts @@ -43,12 +43,11 @@ export function getAggregatedSpaceData(es: Client, objectTypes: string[]) { return es.search({ index: ALL_SAVED_OBJECT_INDICES, request_cache: false, - body: { - size: 0, - runtime_mappings: { - normalized_namespace: { - type: 'keyword', - script: ` + size: 0, + runtime_mappings: { + normalized_namespace: { + type: 'keyword', + script: ` if (doc["namespaces"].size() > 0) { emit(doc["namespaces"].value); } else if (doc["namespace"].size() > 0) { @@ -57,14 +56,13 @@ export function getAggregatedSpaceData(es: Client, objectTypes: string[]) { emit(doc["legacy-url-alias.targetNamespace"].value); } `, - }, }, - query: { terms: { type: objectTypes } }, - aggs: { - count: { - terms: { field: 'normalized_namespace', missing: DEFAULT_SPACE_ID, size: 10 }, - aggs: { countByType: { terms: { field: 'type', missing: 'UNKNOWN', size: 10 } } }, - }, + }, + query: { terms: { type: objectTypes } }, + aggs: { + count: { + terms: { field: 'normalized_namespace', missing: DEFAULT_SPACE_ID, size: 10 }, + aggs: { countByType: { terms: { field: 'type', missing: 'UNKNOWN', size: 10 } } }, }, }, }); diff --git a/x-pack/test/spaces_api_integration/common/services/test_data_loader.ts b/x-pack/test/spaces_api_integration/common/services/test_data_loader.ts index 5d8868edfd113..b4da9abc88915 100644 --- a/x-pack/test/spaces_api_integration/common/services/test_data_loader.ts +++ b/x-pack/test/spaces_api_integration/common/services/test_data_loader.ts @@ -200,21 +200,18 @@ export function getTestDataLoader({ getService }: Pick>({ index: ALL_SAVED_OBJECT_INDICES, size: 100, - body: { query: { terms: { type: ['index-pattern'] } } }, + query: { terms: { type: ['index-pattern'] } }, }); const docs = multiNamespaceResponse.hits.hits; // Just 21 results, since spaces_2_only, conflict_1a_space_2, conflict_1b_space_2, conflict_1c_space_2, and conflict_2_space_2 got deleted. diff --git a/x-pack/test/spaces_api_integration/common/suites/update_objects_spaces.ts b/x-pack/test/spaces_api_integration/common/suites/update_objects_spaces.ts index c1f5bf68c5da2..5334034f76866 100644 --- a/x-pack/test/spaces_api_integration/common/suites/update_objects_spaces.ts +++ b/x-pack/test/spaces_api_integration/common/suites/update_objects_spaces.ts @@ -104,11 +104,9 @@ export function updateObjectsSpacesTestSuiteFactory( } const searchResponse = await es.search({ index: ALL_SAVED_OBJECT_INDICES, - body: { - size: 0, - query: { terms: { type: ['legacy-url-alias'] } }, - track_total_hits: true, - }, + size: 0, + query: { terms: { type: ['legacy-url-alias'] } }, + track_total_hits: true, }); expect((searchResponse.hits.total as SearchTotalHits).value).to.eql( // Six aliases exist in the test fixtures diff --git a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/metrics_route.ts b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/metrics_route.ts index 2bab3cf0dc577..c6d43ba50d6c5 100644 --- a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/metrics_route.ts +++ b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/metrics_route.ts @@ -251,13 +251,11 @@ export default function ({ getService }: FtrProviderContext) { // modify the rule to get it fire a decryption error await es.updateByQuery({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - script: { - lang: 'painless', - source: 'ctx._source.alert.params.foo = "bar"', - }, - query: { ids: { values: [`alert:${ruleId}`] } }, + script: { + lang: 'painless', + source: 'ctx._source.alert.params.foo = "bar"', }, + query: { ids: { values: [`alert:${ruleId}`] } }, refresh: true, conflicts: 'proceed', }); @@ -283,13 +281,11 @@ export default function ({ getService }: FtrProviderContext) { // modify the rule to get it fire a validation error await es.updateByQuery({ index: ALERTING_CASES_SAVED_OBJECT_INDEX, - body: { - script: { - lang: 'painless', - source: 'ctx._source.alert.params.foo = "bar"', - }, - query: { ids: { values: [`alert:${ruleId}`] } }, + script: { + lang: 'painless', + source: 'ctx._source.alert.params.foo = "bar"', }, + query: { ids: { values: [`alert:${ruleId}`] } }, refresh: true, conflicts: 'proceed', }); diff --git a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/migrations.ts b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/migrations.ts index 31854652cbc67..1d67e02a80d57 100644 --- a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/migrations.ts +++ b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/migrations.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import type { TransportResult } from '@elastic/elasticsearch'; import { ConcreteTaskInstance, @@ -61,11 +61,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { > = await es.search( { index: '.kibana_task_manager', - body: { - query: { - term: { - _id: 'task:be7e1250-3322-11eb-94c1-db6995e8389f', - }, + query: { + term: { + _id: 'task:be7e1250-3322-11eb-94c1-db6995e8389f', }, }, }, @@ -90,11 +88,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { > = await es.search( { index: '.kibana_task_manager', - body: { - query: { - term: { - _id: 'task:d33d7590-8377-11ec-8c11-2dfe94229b95', - }, + query: { + term: { + _id: 'task:d33d7590-8377-11ec-8c11-2dfe94229b95', }, }, }, @@ -144,11 +140,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { - query: { - bool: { - filter: [{ term: { type: 'task' } }], - }, + query: { + bool: { + filter: [{ term: { type: 'task' } }], }, }, }, @@ -173,11 +167,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { - query: { - bool: { - filter: [{ term: { type: 'task' } }], - }, + query: { + bool: { + filter: [{ term: { type: 'task' } }], }, }, }, @@ -203,11 +195,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { - query: { - bool: { - filter: [{ term: { type: 'task' } }], - }, + query: { + bool: { + filter: [{ term: { type: 'task' } }], }, }, }, @@ -242,11 +232,9 @@ export default function createGetTests({ getService }: FtrProviderContext) { { index: '.kibana_task_manager', size: 100, - body: { - query: { - bool: { - filter: [{ term: { type: 'task' } }], - }, + query: { + bool: { + filter: [{ term: { type: 'task' } }], }, }, }, diff --git a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_management.ts b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_management.ts index 33c72ffd1de95..2ce1c8f259591 100644 --- a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_management.ts +++ b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_management.ts @@ -8,7 +8,7 @@ import moment from 'moment'; import { random } from 'lodash'; import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { taskMappings as TaskManagerMapping } from '@kbn/task-manager-plugin/server/saved_objects/mappings'; import { ConcreteTaskInstance, BulkUpdateTaskResult } from '@kbn/task-manager-plugin/server'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -61,25 +61,23 @@ export default function ({ getService }: FtrProviderContext) { await es.deleteByQuery({ index: testHistoryIndex, refresh: true, - body: { query: { term: { type: 'task' } } }, + query: { term: { type: 'task' } }, }); } else { await es.indices.create({ index: testHistoryIndex, - body: { - mappings: { - properties: { - type: { - type: 'keyword', - }, - taskId: { - type: 'keyword', - }, - params: taskManagerIndexMapping.params, - state: taskManagerIndexMapping.state, - runAt: taskManagerIndexMapping.runAt, - } as Record, - }, + mappings: { + properties: { + type: { + type: 'keyword', + }, + taskId: { + type: 'keyword', + }, + params: taskManagerIndexMapping.params, + state: taskManagerIndexMapping.state, + runAt: taskManagerIndexMapping.runAt, + } as Record, }, }); } @@ -137,10 +135,8 @@ export default function ({ getService }: FtrProviderContext) { return es .search({ index: testHistoryIndex, - body: { - query: { - term: { type: 'task' }, - }, + query: { + term: { type: 'task' }, }, }) .then((result) => diff --git a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_priority.ts b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_priority.ts index f8fc3f63987b9..be801955050c3 100644 --- a/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_priority.ts +++ b/x-pack/test/task_manager_claimer_update_by_query/test_suites/task_manager/task_priority.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { estypes } from '@elastic/elasticsearch'; import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server'; import { taskMappings as TaskManagerMapping } from '@kbn/task-manager-plugin/server/saved_objects/mappings'; import { asyncForEach } from '@kbn/std'; @@ -85,11 +85,9 @@ export default function ({ getService }: FtrProviderContext) { return es .search({ index: testHistoryIndex, - body: { - query: { - bool: { - filter, - }, + query: { + bool: { + filter, }, }, }) @@ -103,25 +101,23 @@ export default function ({ getService }: FtrProviderContext) { await es.deleteByQuery({ index: testHistoryIndex, refresh: true, - body: { query: { term: { type: 'task' } } }, + query: { term: { type: 'task' } }, }); } else { await es.indices.create({ index: testHistoryIndex, - body: { - mappings: { - properties: { - type: { - type: 'keyword', - }, - taskId: { - type: 'keyword', - }, - params: taskManagerIndexMapping.params, - state: taskManagerIndexMapping.state, - runAt: taskManagerIndexMapping.runAt, - } as Record, - }, + mappings: { + properties: { + type: { + type: 'keyword', + }, + taskId: { + type: 'keyword', + }, + params: taskManagerIndexMapping.params, + state: taskManagerIndexMapping.state, + runAt: taskManagerIndexMapping.runAt, + } as Record, }, }); } diff --git a/x-pack/test/upgrade_assistant_integration/upgrade_assistant/api_deprecations.ts b/x-pack/test/upgrade_assistant_integration/upgrade_assistant/api_deprecations.ts index d29435ce35843..5b4b89842cf84 100644 --- a/x-pack/test/upgrade_assistant_integration/upgrade_assistant/api_deprecations.ts +++ b/x-pack/test/upgrade_assistant_integration/upgrade_assistant/api_deprecations.ts @@ -157,9 +157,7 @@ export default function ({ getService }: FtrProviderContext) { const { hits } = await es.search<{ 'usage-counter': UsageCountersSavedObject }>({ index: '.kibana_usage_counters', - body: { - query: { bool: { should } }, - }, + query: { bool: { should } }, }); expect(hits.hits.length).to.equal(4); @@ -185,9 +183,7 @@ export default function ({ getService }: FtrProviderContext) { const { hits } = await es.search<{ 'usage-counter': UsageCountersSavedObject }>({ index: '.kibana_usage_counters', - body: { - query: { bool: { should } }, - }, + query: { bool: { should } }, }); expect(hits.hits.length).to.equal(5); diff --git a/x-pack/test_serverless/api_integration/services/index_management/svl_datastreams.helpers.ts b/x-pack/test_serverless/api_integration/services/index_management/svl_datastreams.helpers.ts index 2ec16de0efd2e..f4c33693e9b65 100644 --- a/x-pack/test_serverless/api_integration/services/index_management/svl_datastreams.helpers.ts +++ b/x-pack/test_serverless/api_integration/services/index_management/svl_datastreams.helpers.ts @@ -15,24 +15,21 @@ export function SvlDatastreamsHelpers({ getService }: FtrProviderContext) { // A data stream requires an index template before it can be created. await es.indices.putIndexTemplate({ name, - body: { - // We need to match the names of backing indices with this template. - index_patterns: [name + '*'], - template: { - mappings: { - properties: { - '@timestamp': { - type: 'date', - }, + // We need to match the names of backing indices with this template. + index_patterns: [name + '*'], + template: { + mappings: { + properties: { + '@timestamp': { + type: 'date', }, }, - lifecycle: { - // @ts-expect-error @elastic/elasticsearch enabled prop is not typed yet - enabled: true, - }, }, - data_stream: {}, + lifecycle: { + enabled: true, + }, }, + data_stream: {}, }); await es.indices.createDataStream({ name }); @@ -41,14 +38,12 @@ export function SvlDatastreamsHelpers({ getService }: FtrProviderContext) { const updateIndexTemplateMappings = async (name: string, mappings: any) => { await es.indices.putIndexTemplate({ name, - body: { - // We need to match the names of backing indices with this template. - index_patterns: [name + '*'], - template: { - mappings, - }, - data_stream: {}, + // We need to match the names of backing indices with this template. + index_patterns: [name + '*'], + template: { + mappings, }, + data_stream: {}, }); }; diff --git a/x-pack/test_serverless/api_integration/services/index_management/svl_enrich_policies.helpers.ts b/x-pack/test_serverless/api_integration/services/index_management/svl_enrich_policies.helpers.ts index 53f498f2fe53b..c2e8b20c5bb88 100644 --- a/x-pack/test_serverless/api_integration/services/index_management/svl_enrich_policies.helpers.ts +++ b/x-pack/test_serverless/api_integration/services/index_management/svl_enrich_policies.helpers.ts @@ -24,15 +24,13 @@ export function SvlEnrichPoliciesHelpers({ getService }: FtrProviderContext) { const createIndex = async (indexName: string) => { await es.indices.create({ index: indexName, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - firstName: { - type: 'text', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + firstName: { + type: 'text', }, }, }, diff --git a/x-pack/test_serverless/api_integration/services/slo_api.ts b/x-pack/test_serverless/api_integration/services/slo_api.ts index 96b7f9e518f31..b969f56ca4a8c 100644 --- a/x-pack/test_serverless/api_integration/services/slo_api.ts +++ b/x-pack/test_serverless/api_integration/services/slo_api.ts @@ -165,11 +165,9 @@ export function SloApiProvider({ getService }: FtrProviderContext) { async getSloData({ sloId, indexName }: { sloId: string; indexName: string }) { const response = await es.search({ index: indexName, - body: { - query: { - bool: { - filter: [{ term: { 'slo.id': sloId } }], - }, + query: { + bool: { + filter: [{ term: { 'slo.id': sloId } }], }, }, }); @@ -179,11 +177,9 @@ export function SloApiProvider({ getService }: FtrProviderContext) { return await retry.tryForTime(retryTimeout, async () => { const response = await es.search({ index: indexName, - body: { - query: { - bool: { - filter: [{ term: { 'slo.id': sloId } }], - }, + query: { + bool: { + filter: [{ term: { 'slo.id': sloId } }], }, }, }); diff --git a/x-pack/test_serverless/api_integration/services/transform/security_common.ts b/x-pack/test_serverless/api_integration/services/transform/security_common.ts index 8133af4b1f9db..ff686ff42ebc5 100644 --- a/x-pack/test_serverless/api_integration/services/transform/security_common.ts +++ b/x-pack/test_serverless/api_integration/services/transform/security_common.ts @@ -124,11 +124,9 @@ export function TransformSecurityCommonProvider({ getService }: FtrProviderConte return map; }, {}); const apiKey = await esClient.security.createApiKey({ - body: { - name: `Transform API Key ${user.full_name}`, - role_descriptors: roleDescriptors, - metadata: user, - }, + name: `Transform API Key ${user.full_name}`, + role_descriptors: roleDescriptors, + metadata: user, }); return { user: { name: user.name as USER, roles: user.roles }, apiKey }; }, diff --git a/x-pack/test_serverless/api_integration/test_suites/common/data_view_field_editor/field_preview.ts b/x-pack/test_serverless/api_integration/test_suites/common/data_view_field_editor/field_preview.ts index 2bf02a5d73c64..270d6bfabdf06 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/data_view_field_editor/field_preview.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/data_view_field_editor/field_preview.ts @@ -31,15 +31,13 @@ export default function ({ getService }: FtrProviderContext) { const createIndex = async () => { await es.indices.create({ index: INDEX_NAME, - body: { - mappings: { - properties: { - foo: { - type: 'integer', - }, - bar: { - type: 'keyword', - }, + mappings: { + properties: { + foo: { + type: 'integer', + }, + bar: { + type: 'keyword', }, }, }, diff --git a/x-pack/test_serverless/api_integration/test_suites/common/index_management/create_enrich_policies.ts b/x-pack/test_serverless/api_integration/test_suites/common/index_management/create_enrich_policies.ts index 6f8d921ff9934..a863e4f0ebc1b 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/index_management/create_enrich_policies.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/index_management/create_enrich_policies.ts @@ -35,30 +35,26 @@ export default function ({ getService }: FtrProviderContext) { try { await es.indices.create({ index: INDEX_A_NAME, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - firstName: { - type: 'text', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + firstName: { + type: 'text', }, }, }, }); await es.indices.create({ index: INDEX_B_NAME, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - age: { - type: 'long', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + age: { + type: 'long', }, }, }, diff --git a/x-pack/test_serverless/api_integration/test_suites/common/index_management/datastreams.ts b/x-pack/test_serverless/api_integration/test_suites/common/index_management/datastreams.ts index 14e1a5976b7f8..90a890fdcfcf5 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/index_management/datastreams.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/index_management/datastreams.ts @@ -148,12 +148,10 @@ export default function ({ getService }: FtrProviderContext) { logsdbSettings.forEach(({ enabled, indexMode }) => { it(`returns ${indexMode} index mode if logsdb.enabled setting is ${enabled}`, async () => { await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - logsdb: { - enabled, - }, + persistent: { + cluster: { + logsdb: { + enabled, }, }, }, diff --git a/x-pack/test_serverless/api_integration/test_suites/common/index_management/index_templates.ts b/x-pack/test_serverless/api_integration/test_suites/common/index_management/index_templates.ts index fbacef1aed4f6..1b58588e45d82 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/index_management/index_templates.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/index_management/index_templates.ts @@ -45,9 +45,7 @@ export default function ({ getService }: FtrProviderContext) { templateName = `template-${getRandomString()}`; const indexTemplate = { name: templateName, - body: { - index_patterns: ['test*'], - }, + index_patterns: ['test*'], }; // Create a new index template to test against try { @@ -152,12 +150,10 @@ export default function ({ getService }: FtrProviderContext) { logsdbSettings.forEach(({ enabled, indexMode }) => { it(`returns ${indexMode} index mode if logsdb.enabled setting is ${enabled}`, async () => { await es.cluster.putSettings({ - body: { - persistent: { - cluster: { - logsdb: { - enabled, - }, + persistent: { + cluster: { + logsdb: { + enabled, }, }, }, diff --git a/x-pack/test_serverless/api_integration/test_suites/common/platform_security/authorization.ts b/x-pack/test_serverless/api_integration/test_suites/common/platform_security/authorization.ts index 79c5ef82530d7..398c591414f96 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/platform_security/authorization.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/platform_security/authorization.ts @@ -287,15 +287,13 @@ export default function ({ getService }: FtrProviderContext) { it('should fail when role already exists', async function () { await es.security.putRole({ name: 'test_role', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - }, + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], }); await supertestAdminWithApiKey @@ -317,41 +315,39 @@ export default function ({ getService }: FtrProviderContext) { it('should get roles', async function () { await es.security.putRole({ name: 'role_to_get', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'kibana-.kibana', - privileges: [ - 'feature_dashboard_v2.read', - 'feature_discover_v2.all', - 'feature_ml.all', - ], - resources: ['space:marketing', 'space:sales'], - }, - { - application: 'apm', - privileges: ['apm-privilege'], - resources: ['*'], - }, - ], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], + }, + { + application: 'kibana-.kibana', + privileges: [ + 'feature_dashboard_v2.read', + 'feature_discover_v2.all', + 'feature_ml.all', + ], + resources: ['space:marketing', 'space:sales'], + }, + { + application: 'apm', + privileges: ['apm-privilege'], + resources: ['*'], }, + ], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); @@ -397,61 +393,57 @@ export default function ({ getService }: FtrProviderContext) { it('should get roles by space id', async function () { await es.security.putRole({ name: 'space_role_not_to_get', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: [ - 'feature_dashboard_v2.read', - 'feature_discover_v2.all', - 'feature_ml.all', - ], - resources: ['space:marketing', 'space:sales'], - }, - ], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: [ + 'feature_dashboard_v2.read', + 'feature_discover_v2.all', + 'feature_ml.all', + ], + resources: ['space:marketing', 'space:sales'], }, + ], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); await es.security.putRole({ name: 'space_role_to_get', - body: { - cluster: ['manage'], - indices: [ - { - names: ['logstash-*'], - privileges: ['read', 'view_index_metadata'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: [ - 'feature_dashboard_v2.read', - 'feature_discover_v2.all', - 'feature_ml.all', - ], - resources: ['space:engineering', 'space:sales'], - }, - ], - metadata: { - foo: 'test-metadata', + cluster: ['manage'], + indices: [ + { + names: ['logstash-*'], + privileges: ['read', 'view_index_metadata'], }, - transient_metadata: { - enabled: true, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: [ + 'feature_dashboard_v2.read', + 'feature_discover_v2.all', + 'feature_ml.all', + ], + resources: ['space:engineering', 'space:sales'], }, + ], + metadata: { + foo: 'test-metadata', + }, + transient_metadata: { + enabled: true, }, }); @@ -485,29 +477,27 @@ export default function ({ getService }: FtrProviderContext) { it('should update a role with elasticsearch, kibana and other applications privileges', async function () { await es.security.putRole({ name: 'role_to_update', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'apm', - privileges: ['apm-privilege'], - resources: ['*'], - }, - ], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], + }, + { + application: 'apm', + privileges: ['apm-privilege'], + resources: ['*'], + }, + ], + metadata: { + bar: 'old-metadata', }, }); @@ -584,15 +574,13 @@ export default function ({ getService }: FtrProviderContext) { it(`should update a role adding DLS and FLS privileges`, async function () { await es.security.putRole({ name: 'role_to_update_with_dls_fls', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - }, + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], }); await supertestAdminWithApiKey @@ -628,29 +616,27 @@ export default function ({ getService }: FtrProviderContext) { it(`should not update a role with 'run as' privileges`, async function () { await es.security.putRole({ name: 'role_to_update', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'apm', - privileges: ['apm-privilege'], - resources: ['*'], - }, - ], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], + }, + { + application: 'apm', + privileges: ['apm-privilege'], + resources: ['*'], + }, + ], + metadata: { + bar: 'old-metadata', }, }); @@ -724,29 +710,27 @@ export default function ({ getService }: FtrProviderContext) { it(`should not update a role with remote cluster privileges`, async function () { await es.security.putRole({ name: 'role_to_update', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'apm', - privileges: ['apm-privilege'], - resources: ['*'], - }, - ], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], }, + { + application: 'apm', + privileges: ['apm-privilege'], + resources: ['*'], + }, + ], + metadata: { + bar: 'old-metadata', }, }); @@ -825,29 +809,27 @@ export default function ({ getService }: FtrProviderContext) { it(`should not update a role with remote index privileges`, async function () { await es.security.putRole({ name: 'role_to_update', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'apm', - privileges: ['apm-privilege'], - resources: ['*'], - }, - ], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], }, + { + application: 'apm', + privileges: ['apm-privilege'], + resources: ['*'], + }, + ], + metadata: { + bar: 'old-metadata', }, }); @@ -928,29 +910,27 @@ export default function ({ getService }: FtrProviderContext) { it('should delete an existing role', async function () { await es.security.putRole({ name: 'role_to_delete', - body: { - cluster: ['monitor'], - indices: [ - { - names: ['beats-*'], - privileges: ['write'], - }, - ], - applications: [ - { - application: 'kibana-.kibana', - privileges: ['read'], - resources: ['*'], - }, - { - application: 'apm', - privileges: ['apm-privilege'], - resources: ['*'], - }, - ], - metadata: { - bar: 'old-metadata', + cluster: ['monitor'], + indices: [ + { + names: ['beats-*'], + privileges: ['write'], + }, + ], + applications: [ + { + application: 'kibana-.kibana', + privileges: ['read'], + resources: ['*'], }, + { + application: 'apm', + privileges: ['apm-privilege'], + resources: ['*'], + }, + ], + metadata: { + bar: 'old-metadata', }, }); await supertestAdminWithApiKey.delete('/api/security/role/role_to_delete').expect(204); diff --git a/x-pack/test_serverless/api_integration/test_suites/common/reporting/csv_v2_esql.ts b/x-pack/test_serverless/api_integration/test_suites/common/reporting/csv_v2_esql.ts index 022f22a144b6e..5e5a786b783bd 100644 --- a/x-pack/test_serverless/api_integration/test_suites/common/reporting/csv_v2_esql.ts +++ b/x-pack/test_serverless/api_integration/test_suites/common/reporting/csv_v2_esql.ts @@ -53,15 +53,13 @@ export default ({ getService }: FtrProviderContext) => { log.info(`loading test data`); await es.indices.create({ index: timelessIndexName, - body: { - settings: { number_of_shards: 1 }, - mappings: { - properties: { - eon: { type: 'keyword' }, - era: { type: 'keyword' }, - period: { type: 'keyword' }, - epoch: { type: 'keyword' }, - }, + settings: { number_of_shards: 1 }, + mappings: { + properties: { + eon: { type: 'keyword' }, + era: { type: 'keyword' }, + period: { type: 'keyword' }, + epoch: { type: 'keyword' }, }, }, }); diff --git a/x-pack/test_serverless/functional/test_suites/common/data_usage/main.ts b/x-pack/test_serverless/functional/test_suites/common/data_usage/main.ts index 438bf5ab7ee84..042e9fde0267a 100644 --- a/x-pack/test_serverless/functional/test_suites/common/data_usage/main.ts +++ b/x-pack/test_serverless/functional/test_suites/common/data_usage/main.ts @@ -46,11 +46,9 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { for (const { name } of dataStreamsMockResponse) { await es.indices.putIndexTemplate({ name, - body: { - index_patterns: [name], - data_stream: {}, - priority: 200, - }, + index_patterns: [name], + data_stream: {}, + priority: 200, }); await es.indices.createDataStream({ name }); } diff --git a/x-pack/test_serverless/functional/test_suites/common/data_usage/privileges.ts b/x-pack/test_serverless/functional/test_suites/common/data_usage/privileges.ts index dab301dff34ea..5100e223b1b22 100644 --- a/x-pack/test_serverless/functional/test_suites/common/data_usage/privileges.ts +++ b/x-pack/test_serverless/functional/test_suites/common/data_usage/privileges.ts @@ -42,21 +42,17 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await es.indices.putIndexTemplate({ name: 'test-datastream', - body: { - index_patterns: ['test-datastream'], - data_stream: {}, - priority: 200, - }, + index_patterns: ['test-datastream'], + data_stream: {}, + priority: 200, }); await es.indices.createDataStream({ name: 'test-datastream' }); await es.indices.putIndexTemplate({ name: 'no-permission-test-datastream', - body: { - index_patterns: ['no-permission-test-datastream'], - data_stream: {}, - priority: 200, - }, + index_patterns: ['no-permission-test-datastream'], + data_stream: {}, + priority: 200, }); await es.indices.createDataStream({ name: 'no-permission-test-datastream' }); diff --git a/x-pack/test_serverless/functional/test_suites/common/discover/x_pack/reporting.ts b/x-pack/test_serverless/functional/test_suites/common/discover/x_pack/reporting.ts index b54a55cce68c4..86a344470546e 100644 --- a/x-pack/test_serverless/functional/test_suites/common/discover/x_pack/reporting.ts +++ b/x-pack/test_serverless/functional/test_suites/common/discover/x_pack/reporting.ts @@ -193,7 +193,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const res = await es.bulk({ index: TEST_INDEX_NAME, - body: docs.map((d) => `{"index": {}}\n${JSON.stringify(d)}\n`), + operations: docs.map((d) => `{"index": {}}\n${JSON.stringify(d)}\n`), }); log.info(`Indexed ${res.items.length} test data docs.`); diff --git a/x-pack/test_serverless/functional/test_suites/common/management/data_views/_index_pattern_filter.ts b/x-pack/test_serverless/functional/test_suites/common/management/data_views/_index_pattern_filter.ts index 6a8a4c6f95bdf..ae414d7c33146 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/data_views/_index_pattern_filter.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/data_views/_index_pattern_filter.ts @@ -153,12 +153,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await es.indices.create({ index: additionalIndexWithWrongMapping, - body: { - mappings: { - properties: { - bytes: { - type: 'keyword', - }, + mappings: { + properties: { + bytes: { + type: 'keyword', }, }, }, diff --git a/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts b/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts index 66a0a0f33d545..b1cbd69a5e846 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/index_management/component_templates.ts @@ -41,12 +41,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await es.cluster.putComponentTemplate({ name: TEST_COMPONENT_TEMPLATE, - body: { - template: { - settings: { - index: { - number_of_shards: 1, - }, + template: { + settings: { + index: { + number_of_shards: 1, }, }, }, diff --git a/x-pack/test_serverless/functional/test_suites/common/management/index_management/create_enrich_policy.ts b/x-pack/test_serverless/functional/test_suites/common/management/index_management/create_enrich_policy.ts index d5cd5e450019e..6cd0c1442c12c 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/index_management/create_enrich_policy.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/index_management/create_enrich_policy.ts @@ -27,15 +27,13 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { try { await es.indices.create({ index: INDEX_NAME, - body: { - mappings: { - properties: { - email: { - type: 'text', - }, - age: { - type: 'long', - }, + mappings: { + properties: { + email: { + type: 'text', + }, + age: { + type: 'long', }, }, }, diff --git a/x-pack/test_serverless/functional/test_suites/common/management/index_management/enrich_policies.ts b/x-pack/test_serverless/functional/test_suites/common/management/index_management/enrich_policies.ts index 5c8bd2f45fef9..13167560727df 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/index_management/enrich_policies.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/index_management/enrich_policies.ts @@ -28,12 +28,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { try { await es.indices.create({ index: ENRICH_INDEX_NAME, - body: { - mappings: { - properties: { - name: { - type: 'text', - }, + mappings: { + properties: { + name: { + type: 'text', }, }, }, diff --git a/x-pack/test_serverless/functional/test_suites/common/management/index_management/index_templates.ts b/x-pack/test_serverless/functional/test_suites/common/management/index_management/index_templates.ts index 29b480212cc71..a9431a7cd1734 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/index_management/index_templates.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/index_management/index_templates.ts @@ -53,9 +53,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await es.indices.putIndexTemplate({ name: TEST_TEMPLATE, - body: { - index_patterns: [INDEX_PATTERN], - }, + index_patterns: [INDEX_PATTERN], }); }); diff --git a/x-pack/test_serverless/functional/test_suites/common/management/ingest_pipelines.ts b/x-pack/test_serverless/functional/test_suites/common/management/ingest_pipelines.ts index aa1cb5eee16a7..f6ca002988186 100644 --- a/x-pack/test_serverless/functional/test_suites/common/management/ingest_pipelines.ts +++ b/x-pack/test_serverless/functional/test_suites/common/management/ingest_pipelines.ts @@ -47,7 +47,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { // Create a test pipeline await es.ingest.putPipeline({ id: TEST_PIPELINE_NAME, - body: { processors: [] }, + processors: [], } as IngestPutPipelineRequest); }); diff --git a/x-pack/test_serverless/functional/test_suites/search/inference_management.ts b/x-pack/test_serverless/functional/test_suites/search/inference_management.ts index 168a855e2b5d5..2c9c073d8768d 100644 --- a/x-pack/test_serverless/functional/test_suites/search/inference_management.ts +++ b/x-pack/test_serverless/functional/test_suites/search/inference_management.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type * as estypes from '@elastic/elasticsearch/lib/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { testHasEmbeddedConsole } from './embedded_console'; diff --git a/x-pack/test_serverless/functional/test_suites/search/screenshot_creation/response_ops_docs/stack_connectors/index.ts b/x-pack/test_serverless/functional/test_suites/search/screenshot_creation/response_ops_docs/stack_connectors/index.ts index e5d251e691183..701716433056d 100644 --- a/x-pack/test_serverless/functional/test_suites/search/screenshot_creation/response_ops_docs/stack_connectors/index.ts +++ b/x-pack/test_serverless/functional/test_suites/search/screenshot_creation/response_ops_docs/stack_connectors/index.ts @@ -20,13 +20,11 @@ export default function ({ loadTestFile, getService }: FtrProviderContext) { await browser.setWindowSize(1920, 1080); await es.indices.create({ index: testIndex, - body: { - mappings: { - properties: { - date_updated: { - type: 'date', - format: 'epoch_millis', - }, + mappings: { + properties: { + date_updated: { + type: 'date', + format: 'epoch_millis', }, }, }, diff --git a/x-pack/test_serverless/functional/test_suites/search/search_index_detail.ts b/x-pack/test_serverless/functional/test_suites/search/search_index_detail.ts index abb9f6195dc25..be78fa5889cd0 100644 --- a/x-pack/test_serverless/functional/test_suites/search/search_index_detail.ts +++ b/x-pack/test_serverless/functional/test_suites/search/search_index_detail.ts @@ -102,12 +102,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.svlSearchIndexDetailPage.expectQuickStatsAIMappings(); await es.indices.putMapping({ index: indexName, - body: { - properties: { - my_field: { - type: 'dense_vector', - dims: 3, - }, + properties: { + my_field: { + type: 'dense_vector', + dims: 3, }, }, }); diff --git a/yarn.lock b/yarn.lock index c925ef3cf18b7..822f327663871 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2293,12 +2293,12 @@ "@elastic/transport" "^8.3.1" tslib "^2.4.0" -"@elastic/elasticsearch@^8.17.0": - version "8.17.0" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-8.17.0.tgz#0214265bc04a3fe0d23a410b8d08b28217aac540" - integrity sha512-FZ+gQUrPsMpQ2RRIXwTmCoUeFCEausMhp4eQOyxT9j1cwGXHJrhelR6jffM1SC95kQUkB7+TcTq7oQ+bG2BQ9g== +"@elastic/elasticsearch@9.0.0-alpha.3": + version "9.0.0-alpha.3" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-9.0.0-alpha.3.tgz#7580ca3f984cef7c4a9ecda0c5853dfa4671996d" + integrity sha512-10ZJtFXij0TiDc+5WpDfHB+ckEeeEgo6ZwY4QjjNNEFSLZSx+gg7DBgQkddRYpjBe7VM6dBhY76NkRmgod7p9A== dependencies: - "@elastic/transport" "^8.9.1" + "@elastic/transport" "9.0.0-alpha.1" apache-arrow "^18.0.0" tslib "^2.4.0" @@ -2493,7 +2493,20 @@ undici "^5.28.3" yaml "^2.2.2" -"@elastic/transport@^8.3.1", "@elastic/transport@^8.9.1": +"@elastic/transport@9.0.0-alpha.1": + version "9.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@elastic/transport/-/transport-9.0.0-alpha.1.tgz#4e0f967ffe3369daad5b3cd9bf6f925bcb5c69be" + integrity sha512-2l++SiXgAHVG+d8JpUo2Rskh0ViqnuL1kCaIOxdAOS+GxhbHitYJhsENOIiVhcbSW9bNPjAqgDRu8NZv45g8Eg== + dependencies: + "@opentelemetry/api" "1.x" + debug "^4.3.7" + hpagent "^1.2.0" + ms "^2.1.3" + secure-json-parse "^3.0.1" + tslib "^2.8.1" + undici "^7.2.3" + +"@elastic/transport@^8.3.1": version "8.9.1" resolved "https://registry.yarnpkg.com/@elastic/transport/-/transport-8.9.1.tgz#1acc090ac45903a3d5a8b7269f6ba6410108dc0a" integrity sha512-jasKNQeOb1vNf9aEYg+8zXmetaFjApDTSCC4QTl6aTixvyiRiSLcCiB8P6Q0lY9JIII/BhqNl8WbpFnsKitntw== @@ -17191,7 +17204,7 @@ debug@2.6.9, debug@^2.2.0, debug@^2.3.3, debug@^2.6.0: dependencies: ms "2.0.0" -debug@4, debug@^4.0.0, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.3, debug@^4.3.4, debug@^4.3.5, debug@^4.4.0: +debug@4, debug@^4.0.0, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.3, debug@^4.3.4, debug@^4.3.5, debug@^4.3.7, debug@^4.4.0: version "4.4.0" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.0.tgz#2b3f2aea2ffeb776477460267377dc8710faba8a" integrity sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA== @@ -21027,7 +21040,7 @@ hpack.js@^2.1.6: readable-stream "^2.0.1" wbuf "^1.1.0" -hpagent@^1.0.0: +hpagent@^1.0.0, hpagent@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/hpagent/-/hpagent-1.2.0.tgz#0ae417895430eb3770c03443456b8d90ca464903" integrity sha512-A91dYTeIB6NoXG+PxTQpCCDDnfHsW9kc06Lvpu1TEe9gnd6ZFeiBoRO9JvzEv6xK7EX97/dUE8g/vBMTqTS3CA== @@ -29773,6 +29786,11 @@ secure-json-parse@^2.4.0, secure-json-parse@^2.7.0: resolved "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz" integrity sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw== +secure-json-parse@^3.0.1: + version "3.0.2" + resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-3.0.2.tgz#255b03bb0627ba5805f64f384b0a7691d8cb021b" + integrity sha512-H6nS2o8bWfpFEV6U38sOSjS7bTbdgbCGU9wEM6W14P5H0QOsz94KCusifV44GpHDTu2nqZbuDNhTzu+mjDSw1w== + seedrandom@^3.0.5: version "3.0.5" resolved "https://registry.yarnpkg.com/seedrandom/-/seedrandom-3.0.5.tgz#54edc85c95222525b0c7a6f6b3543d8e0b3aa0a7" @@ -32147,7 +32165,7 @@ tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== -tslib@^2.0.0, tslib@^2.0.1, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.3.1, tslib@^2.4.0, tslib@^2.5.0, tslib@^2.6.2, tslib@^2.8.0: +tslib@^2.0.0, tslib@^2.0.1, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.3.1, tslib@^2.4.0, tslib@^2.5.0, tslib@^2.6.2, tslib@^2.8.0, tslib@^2.8.1: version "2.8.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f" integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== @@ -32413,6 +32431,11 @@ undici@^6.12.0: resolved "https://registry.yarnpkg.com/undici/-/undici-6.19.2.tgz#231bc5de78d0dafb6260cf454b294576c2f3cd31" integrity sha512-JfjKqIauur3Q6biAtHJ564e3bWa8VvT+7cSiOJHFbX4Erv6CLGDpg8z+Fmg/1OI/47RA+GI2QZaF48SSaLvyBA== +undici@^7.2.3: + version "7.3.0" + resolved "https://registry.yarnpkg.com/undici/-/undici-7.3.0.tgz#87e48cc9728f3d09bf7b34635e9b63886873ac3e" + integrity sha512-Qy96NND4Dou5jKoSJ2gm8ax8AJM/Ey9o9mz7KN1bb9GP+G0l20Zw8afxTnY2f4b7hmhn/z8aC2kfArVQlAhFBw== + unfetch@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/unfetch/-/unfetch-4.2.0.tgz#7e21b0ef7d363d8d9af0fb929a5555f6ef97a3be"