"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dedupeAggs = dedupeAggs; var _get_group_by_key = require("./operations/definitions/get_group_by_key"); var _to_expression = require("./to_expression"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ /** * Consolidates duplicate agg expression builders to increase performance */ function dedupeAggs(_aggs, _esAggsIdMap, aggExpressionToEsAggsIdMap, allOperations) { let aggs = [..._aggs]; const esAggsIdMap = { ..._esAggsIdMap }; const aggsByArgs = (0, _get_group_by_key.groupByKey)(aggs, expressionBuilder => { for (const operation of allOperations) { var _operation$getGroupBy; const groupKey = (_operation$getGroupBy = operation.getGroupByKey) === null || _operation$getGroupBy === void 0 ? void 0 : _operation$getGroupBy.call(operation, expressionBuilder); if (groupKey) { return `${operation.type}-${groupKey}`; } } }); const termsFuncs = aggs.map(agg => agg.functions[0]).filter(func => func.name === 'aggTerms'); // collapse each group into a single agg expression builder Object.values(aggsByArgs).forEach(expressionBuilders => { if (expressionBuilders.length <= 1) { // don't need to optimize if there aren't more than one return; } const [firstExpressionBuilder, ...restExpressionBuilders] = expressionBuilders; // throw away all but the first expression builder aggs = aggs.filter(aggBuilder => !restExpressionBuilders.includes(aggBuilder)); const firstEsAggsId = aggExpressionToEsAggsIdMap.get(firstExpressionBuilder); if (firstEsAggsId === undefined) { throw new Error('Could not find current column ID for expression builder'); } restExpressionBuilders.forEach(expressionBuilder => { const currentEsAggsId = aggExpressionToEsAggsIdMap.get(expressionBuilder); if (currentEsAggsId === undefined) { throw new Error('Could not find current column ID for expression builder'); } esAggsIdMap[firstEsAggsId].push(...esAggsIdMap[currentEsAggsId]); delete esAggsIdMap[currentEsAggsId]; termsFuncs.forEach(func => { var _func$getArgument; if (((_func$getArgument = func.getArgument('orderBy')) === null || _func$getArgument === void 0 ? void 0 : _func$getArgument[0]) === (0, _to_expression.extractAggId)(currentEsAggsId)) { func.replaceArgument('orderBy', [(0, _to_expression.extractAggId)(firstEsAggsId)]); } }); }); }); return { aggs, esAggsIdMap }; }