import { ElasticsearchClient } from 'kibana/server' ; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey' ; import { CorrelationsParams } from '../../../../common/correlations/types' ; import { TRANSACTION_DURATION } from '../../../../common/elasticsearch_fieldnames' ; import { getQueryWithParams } from './get_query_with_params' ; import { getRequestBase } from './get_request_base' ; export const getTransactionDurationRangesRequest = ( params , ranges ) : estypes . SearchRequest => ( { ... getRequestBase ( params ) , body : { query : getQueryWithParams ( { params } ) , size : 0 , aggs : { latency_ranges : { range : { field : TRANSACTION_DURATION , ranges , } , } , } , } , } ) ; interface Aggs { latency_ranges : { buckets : Array < { doc_count : number ; } > ; } ; } /**
 * Compute the actual percentile bucket counts and actual fractions
 */ export const fetchTransactionDurationFractions = async ( esClient , params , ranges ) : Promise < { fractions : number [ ] ; totalDocCount : number ; } > => { const resp = await esClient . search < unknown , Aggs > ( getTransactionDurationRangesRequest ( params , ranges ) ) ; if ( ( resp . body . hits . total as estypes . SearchTotalHits ) . value === 0 ) { return { fractions : [ ] , totalDocCount : 0 , } ; } if ( resp . body . aggregations === undefined ) { throw new Error ( 'fetchTransactionDurationFractions failed, did not return aggregations.' ) ; } const buckets = resp . body . aggregations . latency_ranges ?. buckets ; const totalDocCount = buckets . reduce ( ( acc , bucket ) => { return acc + bucket . doc_count ; } , 0 ) ; return { fractions : buckets . map ( ( bucket ) => bucket . doc_count / totalDocCount ) , totalDocCount , } ; } ;