"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createServerResultNode = createServerResultNode; exports.fetchTopNodes = fetchTopNodes; var _style_choices = require("../helpers/style_choices"); /* * 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. */ const DEFAULT_SHARD_SIZE = 5000; function createSamplerSearchBody(aggs, shardSize = DEFAULT_SHARD_SIZE) { return { size: 0, aggs: { sample: { sampler: { shard_size: shardSize }, aggs } } }; } function createTopTermsAggName(fieldName) { return `top_values_${fieldName}`; } function createTopTermsSubAgg(field, size = 10) { return { [createTopTermsAggName(field)]: { terms: { field, size } } }; } // TODO use elasticsearch types here function getTopTermsResult(response, fieldName) { if (!response.aggregations) { return []; } return response.aggregations.sample[createTopTermsAggName(fieldName)].buckets.map(bucket => bucket.key); } function createServerResultNode(fieldName, term, allFields) { const field = allFields.find(({ name }) => name === fieldName); if (!field) { throw new Error('Invariant error: field not found'); } return { field: fieldName, term, id: '', color: field.color, icon: (0, _style_choices.getIcon)(field.icon), data: { field: fieldName, term }, label: term }; } async function fetchTopNodes(post, index, fields) { const aggs = fields.map(({ name }) => name).map(fieldName => createTopTermsSubAgg(fieldName)).reduce((allAggs, subAgg) => ({ ...allAggs, ...subAgg })); const body = createSamplerSearchBody(aggs); const response = (await post('../internal/graph/searchProxy', { body: JSON.stringify({ index, body }) })).resp; const nodes = []; fields.forEach(({ name }) => { const topTerms = getTopTermsResult(response, name); const fieldNodes = topTerms.map(term => createServerResultNode(name, term, fields)); nodes.push(...fieldNodes); }); return nodes; }