|
| 1 | +import { projectsIndex, postHeaders } from "../../../config/api"; |
| 2 | +import { AggregationArgs } from "../../../types/commons"; |
| 3 | +import { ProjectAggregationsForAnalyticsTool } from "../../../types/project"; |
| 4 | +import { fillWithMissingYears } from "../../utils/years"; |
| 5 | +import { FIELDS } from "../_utils/constants"; |
| 6 | + |
| 7 | +export async function aggregateProjectsForAnalyticsTool( |
| 8 | + { query }: AggregationArgs |
| 9 | + ): Promise<ProjectAggregationsForAnalyticsTool> { |
| 10 | + const body: any = { |
| 11 | + size: 0, |
| 12 | + query: { |
| 13 | + bool: { |
| 14 | + must: [ |
| 15 | + { |
| 16 | + query_string: { |
| 17 | + query: query || '*', |
| 18 | + fields: FIELDS, |
| 19 | + }, |
| 20 | + } |
| 21 | + ] |
| 22 | + } |
| 23 | + }, |
| 24 | + aggs: { |
| 25 | + projectsCount: { |
| 26 | + value_count: { field: "id.keyword" }, |
| 27 | + }, |
| 28 | + byType: { |
| 29 | + terms: { |
| 30 | + field: "type.keyword", |
| 31 | + size: 500, |
| 32 | + } |
| 33 | + }, |
| 34 | + byYear: { |
| 35 | + terms: { |
| 36 | + field: "year", |
| 37 | + size: 25, |
| 38 | + } |
| 39 | + }, |
| 40 | + byInstitution: { |
| 41 | + terms: { |
| 42 | + field: "participants.structure.id_name.keyword", |
| 43 | + size: 500, |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + const res = await fetch( |
| 49 | + `${projectsIndex}/_search`, |
| 50 | + { method: 'POST', body: JSON.stringify(body), headers: postHeaders }) |
| 51 | + const result = await res.json() |
| 52 | + const { aggregations: data } = result; |
| 53 | + const byInstitution = data?.byInstitution?.buckets |
| 54 | + ?.filter((element) => element.key.split('###')?.[0].match(/^[0-9]{9}[A-Z]{1}$/)) |
| 55 | + .map((element) => { |
| 56 | + return { |
| 57 | + value: element.key.split('###')?.[0], |
| 58 | + label: element.key.split('###')?.[1]?.split('_')?.[1]?.split('|||')?.[0], |
| 59 | + count: element.doc_count, |
| 60 | + } |
| 61 | + }) |
| 62 | + .filter(el => el) || []; |
| 63 | + |
| 64 | + const _100Year = data?.byYear?.buckets && Math.max(...data.byYear.buckets.map((el) => el.doc_count)); |
| 65 | + const byYear = data?.byYear?.buckets?.map((element) => { |
| 66 | + return { |
| 67 | + value: element.key, |
| 68 | + label: element.key, |
| 69 | + count: element.doc_count, |
| 70 | + normalizedCount: element.doc_count * 100 / _100Year, |
| 71 | + } |
| 72 | + }).sort((a, b) => a.label - b.label).reduce(fillWithMissingYears, []) || []; |
| 73 | + const byType = data?.byType?.buckets?.map((element) => { |
| 74 | + return { |
| 75 | + value: element.key, |
| 76 | + label: element.key, |
| 77 | + count: element.doc_count, |
| 78 | + } |
| 79 | + }).filter(el => el) || []; |
| 80 | + const projectsCount = data?.projectsCount?.value || 0; |
| 81 | + return { byInstitution, byYear, byType, projectsCount}; |
| 82 | + |
| 83 | +} |
0 commit comments