EsCountService.java 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. package cn.cslg.pas.service.business.es;
  2. import cn.cslg.pas.common.dto.business.EsCountDTO;
  3. import cn.cslg.pas.common.dto.business.EsCountDetailDTO;
  4. import cn.cslg.pas.common.dto.es.EsCustomFieldValueDTO;
  5. import cn.cslg.pas.common.dto.es.EsDateRangeDTO;
  6. import cn.cslg.pas.common.utils.parseQueryToTree.expressManager;
  7. import cn.cslg.pas.common.utils.parseQueryToTree.operateNode;
  8. import cn.cslg.pas.common.utils.parseQueryToTree.treeNode;
  9. import cn.cslg.pas.common.vo.EsConfigVO;
  10. import cn.cslg.pas.common.vo.business.EsAllCountVO;
  11. import cn.cslg.pas.common.vo.business.EsCountVO;
  12. import cn.cslg.pas.common.vo.es.EsDateRangeVO;
  13. import cn.cslg.pas.domain.es.Patent;
  14. import cn.cslg.pas.factorys.EsCountAnalyseBuilderFactory.EsCountAnalysisBuilderFactory;
  15. import cn.cslg.pas.factorys.EsCountAnalyseBuilderFactory.IEsCountAnalysisBuilder;
  16. import cn.cslg.pas.service.business.CommonService;
  17. import cn.cslg.pas.service.query.FormatQueryService;
  18. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  19. import co.elastic.clients.elasticsearch._types.aggregations.*;
  20. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  21. import co.elastic.clients.elasticsearch.core.SearchRequest;
  22. import co.elastic.clients.elasticsearch.core.SearchResponse;
  23. import com.alibaba.fastjson.JSON;
  24. import lombok.RequiredArgsConstructor;
  25. import org.apache.commons.lang3.StringUtils;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.context.annotation.Lazy;
  28. import org.springframework.stereotype.Service;
  29. import org.springframework.util.CollectionUtils;
  30. import java.text.ParseException;
  31. import java.text.SimpleDateFormat;
  32. import java.util.*;
  33. import java.util.stream.Collectors;
  34. @Service
  35. @RequiredArgsConstructor(onConstructor_ = {@Lazy})
  36. public class EsCountService {
  37. private final List<String> childList = Arrays.asList("field");
  38. private final List<String> nestedList = Arrays.asList("PA", "IN", "PE", "SAT", "MAT", "SRH", "MRH", "MIN");
  39. private final List<String> dateList = Arrays.asList("PD", "AD", "GD");
  40. private final List<String> numberList = Arrays.asList("QPN", "QDPN", "SFN", "IFN", "PFN");
  41. private final ElasticsearchClient client;
  42. @Autowired
  43. private EsCountAnalysisBuilderFactory esCountAnalysisBuilderFactory;
  44. @Autowired
  45. private FormatQueryService formatQueryService;
  46. @Autowired
  47. private EsService esService;
  48. /**
  49. * 聚合统计
  50. *
  51. * @param vo
  52. * @return
  53. * @throws Exception
  54. */
  55. public EsCountDTO esCountAnalysis(EsAllCountVO vo) throws Exception {
  56. List<EsCountVO> countVOS = vo.getCountVOS();
  57. String searchCondition = vo.getCondition();
  58. List<EsCustomFieldValueDTO> customFields = vo.getCustomFields();
  59. Integer taskId = vo.getTaskId();
  60. Integer projectId = vo.getProjectId();
  61. EsCountDTO esCountDTO = new EsCountDTO();
  62. HashMap<String, List<EsCountDetailDTO>> map = new HashMap<>();
  63. List<EsCountDetailDTO> detailDTOS = new ArrayList<>();
  64. if (countVOS.size() > 1) {
  65. EsCountVO countVO = countVOS.get(0);
  66. List<String> values = countVO.getValues();
  67. values.removeIf(i -> i.equals("其他"));
  68. List<EsCountVO> esCountVOS = new ArrayList<>();
  69. esCountVOS.add(countVOS.get(1));
  70. if (StringUtils.isNotEmpty(countVO.getFieldId())) {
  71. if (!CollectionUtils.isEmpty(values)) {
  72. for (String value : values) {
  73. EsCustomFieldValueDTO valueDTO = new EsCustomFieldValueDTO();
  74. valueDTO.setFieldId(countVO.getFieldId());
  75. valueDTO.setFieldValue(Arrays.asList(value));
  76. customFields.add(valueDTO);
  77. this.getReturnData(searchCondition, "",customFields, taskId, projectId,
  78. esCountVOS, detailDTOS, esCountDTO, value, map);
  79. }
  80. }
  81. } else {
  82. for (String value : values) {
  83. String condition = countVO.getField() + " = " + value;
  84. this.getReturnData(searchCondition, condition, customFields, taskId, projectId,
  85. esCountVOS, detailDTOS, esCountDTO, value, map);
  86. }
  87. }
  88. } else {
  89. this.getReturnData(searchCondition, "", customFields, taskId, projectId, countVOS,
  90. detailDTOS, esCountDTO, "", map);
  91. }
  92. esCountDTO.setDetailDTOS(detailDTOS);
  93. return esCountDTO;
  94. }
  95. public void getReturnData(String searchCondition,String condition, List<EsCustomFieldValueDTO> customFields, Integer taskId,
  96. Integer projectId, List<EsCountVO> countVOS, List<EsCountDetailDTO> detailDTOS,
  97. EsCountDTO esCountDTO, String firstName, Map<String, List<EsCountDetailDTO>> map) throws Exception {
  98. if (StringUtils.isNotEmpty(condition)) {
  99. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  100. searchCondition = condition + " AND " + searchCondition;
  101. } else {
  102. searchCondition = condition;
  103. }
  104. }
  105. if (!CollectionUtils.isEmpty(customFields)) {
  106. searchCondition = esService.parseCustomField(customFields);
  107. }
  108. searchCondition = this.getCondition(searchCondition, taskId, projectId);
  109. SearchRequest.Builder builder = new SearchRequest.Builder();
  110. //设置查询索引
  111. builder.index("patent");
  112. //设置查询索引
  113. Query query = null;
  114. if (StringUtils.isNotEmpty(searchCondition)) {
  115. //1. 解析检索条件
  116. treeNode tree = expressManager.getInstance().Parse(searchCondition, false);
  117. //格式化检索式
  118. //3. 从es中检索数据
  119. query = formatQueryService.EsQueryToQuery((operateNode) tree, "patent");
  120. }
  121. for (EsCountVO countVO : countVOS) {
  122. String field = countVO.getField();
  123. Integer topN = countVO.getTopN();
  124. Integer fieldType = null;
  125. String type = countVO.getFieldType();
  126. if (StringUtils.isNotEmpty(type) && type.equals("tree")) {
  127. fieldType = 6;
  128. }
  129. String format = countVO.getFormat();
  130. List<String> values = countVO.getValues();
  131. Aggregation aggregation = this.getAggregation(countVO);
  132. if (query != null) {
  133. Query finalQuery = query;
  134. Aggregation finalAggregation = aggregation;
  135. Aggregation filtersAgg = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  136. .filters(i -> i.array(Arrays.asList(finalQuery))).build())
  137. .aggregations(new HashMap() {{
  138. put("filters_agg", finalAggregation);
  139. }}).build();
  140. builder.aggregations("Agg", filtersAgg);
  141. } else {
  142. builder.aggregations("Agg", aggregation);
  143. }
  144. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  145. Aggregate agg = response.aggregations().get("Agg");
  146. if (query != null) {
  147. String finalSearchCondition = searchCondition;
  148. if (StringUtils.isNotEmpty(field)) {
  149. List<FiltersBucket> filtersBuckets = agg.filters().buckets().array();
  150. if (dateList.contains(field)) {
  151. if (CollectionUtils.isEmpty(values)) {
  152. filtersBuckets.forEach(filtersBucket -> {
  153. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  154. try {
  155. this.getDateCountDTOS(filtersAgg, field, topN, format, detailDTOS, esCountDTO);
  156. } catch (ParseException e) {
  157. e.printStackTrace();
  158. }
  159. });
  160. } else {
  161. filtersBuckets.forEach(filtersBucket -> {
  162. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  163. this.getDateAnalysisDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  164. });
  165. }
  166. } else if (nestedList.contains(field)) {
  167. filtersBuckets.forEach(filtersBucket -> {
  168. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  169. this.getNestedCountDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  170. if (!CollectionUtils.isEmpty(values)) {
  171. esCountDTO.setAllNumber(filtersAgg.nested().docCount());
  172. }
  173. });
  174. } else if (childList.contains(field)) {
  175. if (CollectionUtils.isEmpty(values)) {
  176. Integer finalFieldType = fieldType;
  177. filtersBuckets.forEach(filtersBucket -> {
  178. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  179. this.getChildCountDTOS(filtersAgg, field, finalFieldType, topN, detailDTOS, esCountDTO);
  180. });
  181. } else {
  182. Integer finalFieldType1 = fieldType;
  183. filtersBuckets.forEach(filtersBucket -> {
  184. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  185. this.getChildAnalysisDTOS(filtersAgg, field, finalFieldType1, topN,
  186. detailDTOS, esCountDTO, firstName, map, values);
  187. });
  188. }
  189. } else if (numberList.contains(field)) {
  190. if (CollectionUtils.isEmpty(values)) {
  191. } else {
  192. filtersBuckets.forEach(filtersBucket -> {
  193. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  194. this.getNumberAnalysisDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  195. });
  196. }
  197. } else {
  198. filtersBuckets.forEach(filtersBucket -> {
  199. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  200. this.getTermCountDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  201. });
  202. }
  203. } else {
  204. this.getFilterCountDTO(agg, finalSearchCondition, detailDTOS);
  205. }
  206. } else {
  207. if (dateList.contains(field)) {
  208. if (CollectionUtils.isEmpty(values)) {
  209. this.getDateCountDTOS(agg, field, topN, format, detailDTOS, esCountDTO);
  210. } else {
  211. this.getDateAnalysisDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  212. }
  213. } else if (nestedList.contains(field)) {
  214. this.getNestedCountDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  215. if (!CollectionUtils.isEmpty(values)) {
  216. esCountDTO.setAllNumber(agg.nested().docCount());
  217. }
  218. } else if (childList.contains(field)) {
  219. if (CollectionUtils.isEmpty(values)) {
  220. this.getChildCountDTOS(agg, field, fieldType, topN, detailDTOS, esCountDTO);
  221. } else {
  222. this.getChildAnalysisDTOS(agg, field, fieldType, topN,
  223. detailDTOS, esCountDTO, firstName, map, values);
  224. }
  225. } else if (numberList.contains(field)) {
  226. this.getNumberAnalysisDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  227. } else {
  228. this.getTermCountDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  229. }
  230. }
  231. esCountDTO.setCondition(searchCondition);
  232. esCountDTO.setAnalyseMap(map);
  233. }
  234. }
  235. public EsDateRangeDTO getFieldRange(EsDateRangeVO rangeVO) throws Exception {
  236. String searchCondition = rangeVO.getCondition();
  237. String field = rangeVO.getField();
  238. List<EsCustomFieldValueDTO> customFields = rangeVO.getCustomFields();
  239. if (!CollectionUtils.isEmpty(customFields)) {
  240. searchCondition = esService.parseCustomField(customFields);
  241. }
  242. Integer taskId = rangeVO.getTaskId();
  243. Integer projectId = rangeVO.getProjectId();
  244. searchCondition = this.getCondition(searchCondition, taskId, projectId);
  245. SearchRequest.Builder builder = new SearchRequest.Builder();
  246. //设置查询索引
  247. builder.index("patent");
  248. //设置查询索引
  249. Query query = null;
  250. if (StringUtils.isNotEmpty(searchCondition)) {
  251. //1. 解析检索条件
  252. treeNode tree = expressManager.getInstance().Parse(searchCondition, false);
  253. //格式化检索式
  254. //3. 从es中检索数据
  255. query = formatQueryService.EsQueryToQuery((operateNode) tree, "patent");
  256. }
  257. String esField = "";
  258. if (StringUtils.isNotEmpty(field)) {
  259. switch (field) {
  260. case "AD":
  261. esField = "app_date";
  262. break;
  263. case "PD":
  264. esField = "public_date";
  265. break;
  266. case "GD":
  267. esField = "grant_date";
  268. break;
  269. }
  270. }
  271. EsDateRangeDTO rangeDTO = new EsDateRangeDTO();
  272. if (StringUtils.isNotEmpty(esField)) {
  273. String finalEsField = esField;
  274. Query finalQuery = query;
  275. Aggregation min = AggregationBuilders.min(i -> i.field(finalEsField).format("yyyy"));
  276. Aggregation filtersAgg = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  277. .filters(i -> i.array(Arrays.asList(finalQuery))).build())
  278. .aggregations(new HashMap() {{
  279. put("filters_agg", min);
  280. }}).build();
  281. Aggregation max = AggregationBuilders.max(i -> i.field(finalEsField).format("yyyy"));
  282. Aggregation maxFilters = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  283. .filters(i -> i.array(Arrays.asList(finalQuery))).build())
  284. .aggregations(new HashMap() {{
  285. put("max_agg", max);
  286. }}).build();
  287. builder.aggregations("minAgg", filtersAgg);
  288. builder.aggregations("maxAgg", maxFilters);
  289. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  290. Aggregate minAgg = response.aggregations().get("minAgg");
  291. if (minAgg != null) {
  292. List<FiltersBucket> list = minAgg.filters().buckets().array();
  293. for (FiltersBucket bucket : list) {
  294. Aggregate aggregate = bucket.aggregations().get("filters_agg");
  295. String minValue = aggregate.min().valueAsString();
  296. rangeDTO.setMinDate(minValue);
  297. }
  298. }
  299. Aggregate maxAgg = response.aggregations().get("maxAgg");
  300. if (maxAgg != null) {
  301. List<FiltersBucket> list = maxAgg.filters().buckets().array();
  302. for (FiltersBucket bucket : list) {
  303. Aggregate aggregate = bucket.aggregations().get("max_agg");
  304. String maxValue = aggregate.max().valueAsString();
  305. rangeDTO.setMaxDate(maxValue);
  306. }
  307. }
  308. }
  309. return rangeDTO;
  310. }
  311. /**
  312. * 查询共用Aggregation
  313. *
  314. * @param countVO
  315. * @return
  316. * @throws Exception
  317. */
  318. public Aggregation getAggregation(EsCountVO countVO) throws Exception {
  319. String field = countVO.getField();
  320. Integer topN = countVO.getTopN();
  321. Boolean ifHaveChild = countVO.getIfHaveChild();
  322. String fieldId = countVO.getFieldId();
  323. Integer fieldType = null;
  324. String type = countVO.getFieldType();
  325. if (StringUtils.isNotEmpty(type) && type.equals("tree")) {
  326. fieldType = 6;
  327. }
  328. String format = countVO.getFormat();
  329. String valueOne = countVO.getValueOne();
  330. String valueTwo = countVO.getValueTwo();
  331. List<String> values = countVO.getValues();
  332. IEsCountAnalysisBuilder iEsCountAnalysisBuilder = null;
  333. String json = CommonService.readJsonFile("esCountAnalysis.json");
  334. List<EsConfigVO> esConfigVOS = JSON.parseArray(json, EsConfigVO.class);
  335. EsConfigVO esConfigVO = esConfigVOS.stream().filter(item -> item.getField().equals(field))
  336. .findFirst().orElse(null);
  337. Aggregation aggregation = null;
  338. if (esConfigVO != null) {
  339. iEsCountAnalysisBuilder = esCountAnalysisBuilderFactory.getClass(esConfigVO.getEsClass());
  340. iEsCountAnalysisBuilder.setField(esConfigVO.getEsField());
  341. iEsCountAnalysisBuilder.setValueOne(valueOne);
  342. iEsCountAnalysisBuilder.setValueTwo(valueTwo);
  343. iEsCountAnalysisBuilder.setValues(values);
  344. iEsCountAnalysisBuilder.setFieldId(fieldId);
  345. iEsCountAnalysisBuilder.setFieldType(String.valueOf(fieldType));
  346. iEsCountAnalysisBuilder.setTopN(topN);
  347. iEsCountAnalysisBuilder.setFormat(format);
  348. iEsCountAnalysisBuilder.setIfHaveChild(ifHaveChild);
  349. if (iEsCountAnalysisBuilder.getField().contains(".")) {
  350. String path = iEsCountAnalysisBuilder.getField()
  351. .substring(0, iEsCountAnalysisBuilder.getField().indexOf("."));
  352. iEsCountAnalysisBuilder.setPath(path);
  353. }
  354. aggregation = iEsCountAnalysisBuilder.createCountAnalyseAgg();
  355. }
  356. return aggregation;
  357. }
  358. /**
  359. * 获取筛选条件
  360. *
  361. * @param taskId
  362. * @param projectId
  363. * @return
  364. */
  365. public String getCondition(String searchCondition, Integer taskId, Integer projectId) {
  366. if (taskId != null) {
  367. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  368. searchCondition = "taskId = " + taskId + " AND " + searchCondition;
  369. } else {
  370. searchCondition = "taskId = " + taskId;
  371. }
  372. } else {
  373. if (projectId != null) {
  374. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  375. searchCondition = "projectId = " + projectId + " AND " + searchCondition;
  376. } else {
  377. searchCondition = "projectId = " + projectId;
  378. }
  379. }
  380. }
  381. return searchCondition;
  382. }
  383. /**
  384. * 获取Filter聚合返回数据
  385. *
  386. * @param agg
  387. * @param condition
  388. * @return
  389. */
  390. public void getFilterCountDTO(Aggregate agg, String condition, List<EsCountDetailDTO> detailDTOS) {
  391. EsCountDetailDTO filterDTO = new EsCountDetailDTO();
  392. filterDTO.setField("condition");
  393. filterDTO.setName(condition);
  394. filterDTO.setNumber(agg.filter().docCount());
  395. if (filterDTO.getNumber() > 0) {
  396. detailDTOS.add(filterDTO);
  397. }
  398. }
  399. /**
  400. * 获取Terms聚合后数据
  401. *
  402. * @param agg
  403. * @param field
  404. * @param detailDTOS
  405. */
  406. public void getTermCountDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  407. EsCountDTO esCountDTO, String firstName,
  408. Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  409. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  410. EsCountDetailDTO countDTO = new EsCountDetailDTO();
  411. countDTO.setField(field);
  412. countDTO.setName("其他");
  413. countDTO.setNumber(agg.sterms().sumOtherDocCount());
  414. countDTO.setTopN(topN);
  415. detailDTOS.add(countDTO);
  416. List<StringTermsBucket> list = agg.sterms().buckets().array();
  417. list.forEach(bucket -> {
  418. EsCountDetailDTO dto = new EsCountDetailDTO();
  419. dto.setField(field);
  420. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  421. dto.setName(bucket.key().stringValue());
  422. dto.setNumber(bucket.docCount());
  423. dto.setTopN(topN);
  424. dto.setFirstName(firstName);
  425. if (aggregate != null) {
  426. dto.setNumber(aggregate.filter().docCount());
  427. }
  428. if (dto.getNumber() > 0) {
  429. countDetailDTOS.add(dto);
  430. }
  431. });
  432. List<String> strs = new ArrayList<>();
  433. if (!CollectionUtils.isEmpty(values)) {
  434. strs.addAll(values);
  435. }
  436. if (StringUtils.isNotEmpty(firstName)) {
  437. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  438. if (countDetailDTOS.size() != values.size()) {
  439. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  440. strs.removeIf(i -> i.equals(detailDTO.getName()));
  441. }
  442. for (String value : strs) {
  443. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  444. detailDTO.setName(value);
  445. detailDTO.setFirstName(firstName);
  446. detailDTO.setField(field);
  447. detailDTO.setNumber(0L);
  448. detailDTO.setTopN(topN);
  449. countDetailDTOS.add(detailDTO);
  450. }
  451. } else if (countDetailDTOS.isEmpty()) {
  452. for (String value : values) {
  453. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  454. detailDTO.setName(value);
  455. detailDTO.setFirstName(firstName);
  456. detailDTO.setField(field);
  457. detailDTO.setNumber(0L);
  458. detailDTO.setTopN(topN);
  459. countDetailDTOS.add(detailDTO);
  460. }
  461. }
  462. map.put(firstName, countDetailDTOS);
  463. } else {
  464. detailDTOS.addAll(countDetailDTOS);
  465. }
  466. }
  467. /**
  468. * 获取children聚合后数据
  469. *
  470. * @param agg
  471. * @param field
  472. * @param detailDTOS
  473. */
  474. public void getChildCountDTOS(Aggregate agg, String field, Integer fieldType, Integer topN,
  475. List<EsCountDetailDTO> detailDTOS, EsCountDTO esCountDTO) {
  476. esCountDTO.setAllNumber(agg.children().docCount());
  477. Aggregate childAgg = agg.children().aggregations().get("childAgg");
  478. List<StringTermsBucket> list = childAgg.sterms().buckets().array();
  479. list.forEach(bucket -> {
  480. Aggregate aggregate = bucket.aggregations().get("termAgg");
  481. List<StringTermsBucket> termsBuckets = aggregate.sterms().buckets().array();
  482. termsBuckets.forEach(termsBucket -> {
  483. Aggregate termAgg = termsBucket.aggregations().get("filterAgg");
  484. long count = termAgg.filter().docCount();
  485. if (count > 0) {
  486. EsCountDetailDTO dto = new EsCountDetailDTO();
  487. dto.setField(field);
  488. dto.setName(termsBucket.key().stringValue());
  489. dto.setNumber(termsBucket.docCount());
  490. dto.setNumber(count);
  491. dto.setTopN(topN);
  492. if (dto.getNumber() > 0) {
  493. detailDTOS.add(dto);
  494. if (fieldType == null || fieldType != 6) {
  495. Long docCount = aggregate.sterms().sumOtherDocCount();
  496. EsCountDetailDTO detail = new EsCountDetailDTO();
  497. detail.setField(field);
  498. detail.setName("未选择");
  499. detail.setNumber(docCount);
  500. detail.setTopN(topN);
  501. if (!detailDTOS.contains(detail)) {
  502. detailDTOS.add(detail);
  503. }
  504. }
  505. }
  506. }
  507. });
  508. });
  509. }
  510. /**
  511. * 获取children分析后数据
  512. *
  513. * @param agg
  514. * @param field
  515. * @param detailDTOS
  516. */
  517. public void getChildAnalysisDTOS(Aggregate agg, String field, Integer fieldType, Integer topN,
  518. List<EsCountDetailDTO> detailDTOS, EsCountDTO esCountDTO,
  519. String firstName, Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  520. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  521. Aggregate childAgg = agg.children().aggregations().get("childAgg");
  522. List<StringTermsBucket> list = childAgg.sterms().buckets().array();
  523. list.forEach(bucket -> {
  524. esCountDTO.setAllNumber(bucket.docCount());
  525. Aggregate aggregate = bucket.aggregations().get("termAgg");
  526. List<StringTermsBucket> termsBuckets = aggregate.sterms().buckets().array();
  527. termsBuckets.forEach(termsBucket -> {
  528. EsCountDetailDTO dto = new EsCountDetailDTO();
  529. dto.setField(field);
  530. dto.setName(termsBucket.key().stringValue());
  531. dto.setNumber(termsBucket.docCount());
  532. dto.setFirstName(firstName);
  533. dto.setTopN(topN);
  534. countDetailDTOS.add(dto);
  535. if (fieldType == null || fieldType != 6) {
  536. Long docCount = aggregate.sterms().sumOtherDocCount();
  537. EsCountDetailDTO detail = new EsCountDetailDTO();
  538. detail.setField(field);
  539. detail.setName("未选择");
  540. detail.setNumber(docCount);
  541. detail.setTopN(topN);
  542. if (!countDetailDTOS.contains(detail)) {
  543. countDetailDTOS.add(detail);
  544. }
  545. }
  546. // if (dto.getNumber() > 0) {
  547. // detailDTOS.add(dto);
  548. // if (fieldType == null || fieldType != 6) {
  549. // Long docCount = aggregate.sterms().sumOtherDocCount();
  550. // EsCountDetailDTO detail = new EsCountDetailDTO();
  551. // detail.setField(field);
  552. // detail.setName("未选择");
  553. // detail.setNumber(docCount);
  554. // detail.setTopN(topN);
  555. // if (!detailDTOS.contains(detail)) {
  556. // detailDTOS.add(detail);
  557. // }
  558. // }
  559. // }
  560. });
  561. });
  562. List<String> strs = new ArrayList<>();
  563. if (!CollectionUtils.isEmpty(values)) {
  564. strs.addAll(values);
  565. }
  566. if (StringUtils.isNotEmpty(firstName)) {
  567. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  568. if (countDetailDTOS.size() != values.size()) {
  569. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  570. strs.removeIf(i -> i.equals(detailDTO.getName()));
  571. }
  572. for (String value : strs) {
  573. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  574. detailDTO.setName(value);
  575. detailDTO.setFirstName(firstName);
  576. detailDTO.setField(field);
  577. detailDTO.setNumber(0L);
  578. detailDTO.setTopN(topN);
  579. countDetailDTOS.add(detailDTO);
  580. }
  581. } else if (countDetailDTOS.isEmpty()) {
  582. for (String value : values) {
  583. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  584. detailDTO.setName(value);
  585. detailDTO.setFirstName(firstName);
  586. detailDTO.setField(field);
  587. detailDTO.setNumber(0L);
  588. detailDTO.setTopN(topN);
  589. countDetailDTOS.add(detailDTO);
  590. }
  591. }
  592. map.put(firstName, countDetailDTOS);
  593. } else {
  594. detailDTOS.addAll(countDetailDTOS);
  595. }
  596. }
  597. /**
  598. * 获取range分析后数据
  599. *
  600. * @param agg
  601. * @param field
  602. * @param detailDTOS
  603. */
  604. public void getNumberAnalysisDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  605. EsCountDTO esCountDTO, String firstName,
  606. Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  607. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  608. List<RangeBucket> list = agg.range().buckets().array();
  609. for (RangeBucket bucket : list) {
  610. EsCountDetailDTO dto = new EsCountDetailDTO();
  611. dto.setField(field);
  612. dto.setName(bucket.key());
  613. dto.setNumber(bucket.docCount());
  614. dto.setTopN(topN);
  615. dto.setFirstName(firstName);
  616. countDetailDTOS.add(dto);
  617. // if (dto.getNumber() > 0) {
  618. // detailDTOS.add(dto);
  619. // }
  620. }
  621. List<String> strs = new ArrayList<>();
  622. if (!CollectionUtils.isEmpty(values)) {
  623. strs.addAll(values);
  624. }
  625. if (StringUtils.isNotEmpty(firstName)) {
  626. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  627. if (countDetailDTOS.size() != values.size()) {
  628. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  629. strs.removeIf(i -> i.equals(detailDTO.getName()));
  630. }
  631. for (String value : strs) {
  632. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  633. detailDTO.setName(value);
  634. detailDTO.setFirstName(firstName);
  635. detailDTO.setField(field);
  636. detailDTO.setNumber(0L);
  637. detailDTO.setTopN(topN);
  638. countDetailDTOS.add(detailDTO);
  639. }
  640. } else if (countDetailDTOS.isEmpty()) {
  641. for (String value : values) {
  642. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  643. detailDTO.setName(value);
  644. detailDTO.setFirstName(firstName);
  645. detailDTO.setField(field);
  646. detailDTO.setNumber(0L);
  647. detailDTO.setTopN(topN);
  648. countDetailDTOS.add(detailDTO);
  649. }
  650. }
  651. map.put(firstName, countDetailDTOS);
  652. } else {
  653. detailDTOS.addAll(countDetailDTOS);
  654. }
  655. }
  656. /**
  657. * 获取dateHistogram聚合后数据
  658. *
  659. * @param agg
  660. * @param field
  661. * @param detailDTOS
  662. */
  663. public void getDateCountDTOS(Aggregate agg, String field, Integer topN, String format, List<EsCountDetailDTO> detailDTOS, EsCountDTO esCountDTO) throws ParseException {
  664. List<DateHistogramBucket> list = agg.dateHistogram().buckets().array();
  665. esCountDTO.setAllNumber(Long.valueOf(String.valueOf(list.size())));
  666. List<EsCountDetailDTO> esCountDetailDTOS = new ArrayList<>();
  667. if (StringUtils.isNotEmpty(format) && format.equals("半年")) {
  668. List<EsCountDetailDTO> detailDTOList = new ArrayList<>();
  669. for (DateHistogramBucket bucket : list) {
  670. String year = bucket.keyAsString();
  671. SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
  672. String startMonth = year + "-01";
  673. Calendar calendar = Calendar.getInstance();
  674. Date date = monthFormat.parse(startMonth);
  675. calendar.setTime(date);
  676. calendar.add(Calendar.MONTH, 6);
  677. Date halfYearDate = calendar.getTime();
  678. Aggregate aggregate = bucket.aggregations().get("halfYearAgg");
  679. List<DateHistogramBucket> buckets = aggregate.dateHistogram().buckets().array();
  680. long h1Count = 0;
  681. long h2Count = 0;
  682. for (DateHistogramBucket histogramBucket : buckets) {
  683. String key = histogramBucket.keyAsString();
  684. Date month = monthFormat.parse(key);
  685. EsCountDetailDTO dto = new EsCountDetailDTO();
  686. dto.setField(field);
  687. dto.setName(year + "-H1");
  688. dto.setNumber(h1Count);
  689. dto.setTopN(topN);
  690. EsCountDetailDTO dto2 = new EsCountDetailDTO();
  691. dto2.setField(field);
  692. dto2.setName(year + "-H2");
  693. dto2.setNumber(h2Count);
  694. dto2.setTopN(topN);
  695. if (month.before(halfYearDate)) {
  696. h1Count += histogramBucket.docCount();
  697. dto.setNumber(h1Count);
  698. }
  699. if (month.after(halfYearDate)) {
  700. h2Count += histogramBucket.docCount();
  701. dto2.setNumber(h2Count);
  702. }
  703. detailDTOList.add(dto);
  704. detailDTOList.add(dto2);
  705. }
  706. }
  707. Map<String, List<EsCountDetailDTO>> map = detailDTOList.stream().collect(Collectors.groupingBy(EsCountDetailDTO::getName));
  708. for (String key : map.keySet()) {
  709. List<EsCountDetailDTO> dtoList = map.get(key);
  710. long sum = dtoList.stream().mapToLong(EsCountDetailDTO::getNumber).sum();
  711. EsCountDetailDTO detailDTO = dtoList.get(0);
  712. detailDTO.setNumber(sum);
  713. esCountDetailDTOS.add(detailDTO);
  714. }
  715. } else if (StringUtils.isNotEmpty(format) && format.equals("季")) {
  716. for (DateHistogramBucket bucket : list) {
  717. String yearMonth = bucket.keyAsString();
  718. String year = yearMonth.substring(0, yearMonth.indexOf("-"));
  719. String firstQuarter = year + "-01";
  720. String secondQuarter = year + "-04";
  721. String thirdQuarter = year + "-07";
  722. String forthQuarter = year + "-10";
  723. String firstQ = year + "-Q1";
  724. String secondQ = year + "-Q2";
  725. String thirdQ = year + "-Q3";
  726. String forthQ = year + "-Q4";
  727. EsCountDetailDTO dto = new EsCountDetailDTO();
  728. dto.setField(field);
  729. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  730. if (yearMonth.equals(firstQuarter)) {
  731. dto.setName(firstQ);
  732. } else if (yearMonth.equals(secondQuarter)) {
  733. dto.setName(secondQ);
  734. } else if (yearMonth.equals(thirdQuarter)) {
  735. dto.setName(thirdQ);
  736. } else if (yearMonth.equals(forthQuarter)) {
  737. dto.setName(forthQ);
  738. }
  739. dto.setNumber(bucket.docCount());
  740. dto.setTopN(topN);
  741. if (aggregate != null) {
  742. dto.setNumber(aggregate.filter().docCount());
  743. }
  744. esCountDetailDTOS.add(dto);
  745. }
  746. } else {
  747. list.forEach(bucket -> {
  748. EsCountDetailDTO dto = new EsCountDetailDTO();
  749. dto.setField(field);
  750. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  751. dto.setName(bucket.keyAsString());
  752. dto.setNumber(bucket.docCount());
  753. dto.setTopN(topN);
  754. if (aggregate != null) {
  755. dto.setNumber(aggregate.filter().docCount());
  756. }
  757. esCountDetailDTOS.add(dto);
  758. });
  759. }
  760. if (!CollectionUtils.isEmpty(esCountDetailDTOS)) {
  761. List<EsCountDetailDTO> collect = esCountDetailDTOS.stream()
  762. .sorted(Comparator.comparing(EsCountDetailDTO::getName).reversed()).limit(topN).collect(Collectors.toList());
  763. detailDTOS.addAll(collect);
  764. }
  765. // EsCountDetailDTO countDTO = new EsCountDetailDTO();
  766. // countDTO.setField(field);
  767. // countDTO.setName("其他");
  768. // if (list.size() > topN) {
  769. // int sum = list.size() - topN;
  770. // countDTO.setNumber(Long.valueOf(String.valueOf(sum)));
  771. //
  772. // } else {
  773. // countDTO.setNumber(0L);
  774. // }
  775. // countDTO.setTopN(topN);
  776. // detailDTOS.add(countDTO);
  777. }
  778. /**
  779. * 获取dateHistogram分析后数据
  780. *
  781. * @param agg
  782. * @param field
  783. * @param topN
  784. * @param detailDTOS
  785. */
  786. public void getDateAnalysisDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  787. EsCountDTO esCountDTO, String firstName,
  788. Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  789. List<RangeBucket> list1 = agg.dateRange().buckets().array();
  790. List<EsCountDetailDTO> esCountDetailDTOS = new ArrayList<>();
  791. for (RangeBucket bucket : list1) {
  792. EsCountDetailDTO dto = new EsCountDetailDTO();
  793. dto.setFirstName(firstName);
  794. dto.setField(field);
  795. dto.setName(bucket.key());
  796. dto.setNumber(bucket.docCount());
  797. dto.setTopN(topN);
  798. esCountDetailDTOS.add(dto);
  799. }
  800. if (!CollectionUtils.isEmpty(esCountDetailDTOS)) {
  801. List<EsCountDetailDTO> collect = esCountDetailDTOS.stream()
  802. .sorted(Comparator.comparing(EsCountDetailDTO::getName).reversed()).limit(topN).collect(Collectors.toList());
  803. List<String> strs = new ArrayList<>();
  804. if (!CollectionUtils.isEmpty(values)) {
  805. strs.addAll(values);
  806. }
  807. if (StringUtils.isNotEmpty(firstName)) {
  808. collect.removeIf(dto -> dto.getName().equals("其他"));
  809. if (collect.size() != values.size()) {
  810. for (EsCountDetailDTO detailDTO : collect) {
  811. strs.removeIf(i -> i.equals(detailDTO.getName()));
  812. }
  813. for (String value : strs) {
  814. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  815. detailDTO.setName(value);
  816. detailDTO.setFirstName(firstName);
  817. detailDTO.setField(field);
  818. detailDTO.setNumber(0L);
  819. detailDTO.setTopN(topN);
  820. collect.add(detailDTO);
  821. }
  822. } else if (collect.isEmpty()) {
  823. for (String value : values) {
  824. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  825. detailDTO.setName(value);
  826. detailDTO.setFirstName(firstName);
  827. detailDTO.setField(field);
  828. detailDTO.setNumber(0L);
  829. detailDTO.setTopN(topN);
  830. collect.add(detailDTO);
  831. }
  832. }
  833. map.put(firstName, collect);
  834. } else {
  835. detailDTOS.addAll(collect);
  836. }
  837. }
  838. }
  839. /**
  840. * 获取nested聚合后数据
  841. *
  842. * @param agg
  843. * @param field
  844. * @param detailDTOS
  845. */
  846. public void getNestedCountDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  847. EsCountDTO esCountDTO, String firstName,
  848. Map<String, List<EsCountDetailDTO>> map, List<String> values) {
  849. Aggregate termsAgg = agg.nested().aggregations().get("terms_agg");
  850. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  851. EsCountDetailDTO countDTO = new EsCountDetailDTO();
  852. countDTO.setField(field);
  853. countDTO.setName("其他");
  854. countDTO.setNumber(termsAgg.sterms().sumOtherDocCount());
  855. countDTO.setTopN(topN);
  856. countDetailDTOS.add(countDTO);
  857. List<StringTermsBucket> list = termsAgg.sterms().buckets().array();
  858. list.forEach(bucket -> {
  859. EsCountDetailDTO dto = new EsCountDetailDTO();
  860. dto.setField(field);
  861. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  862. dto.setName(bucket.key().stringValue());
  863. dto.setNumber(bucket.docCount());
  864. dto.setTopN(topN);
  865. dto.setFirstName(firstName);
  866. if (aggregate != null) {
  867. dto.setNumber(aggregate.filter().docCount());
  868. }
  869. countDetailDTOS.add(dto);
  870. // if (dto.getNumber() > 0) {
  871. // detailDTOS.add(dto);
  872. // }
  873. });
  874. List<String> strs = new ArrayList<>();
  875. if (!CollectionUtils.isEmpty(values)) {
  876. strs.addAll(values);
  877. }
  878. if (StringUtils.isNotEmpty(firstName)) {
  879. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  880. if (countDetailDTOS.size() != values.size()) {
  881. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  882. strs.removeIf(i -> i.equals(detailDTO.getName()));
  883. }
  884. for (String value : strs) {
  885. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  886. detailDTO.setName(value);
  887. detailDTO.setFirstName(firstName);
  888. detailDTO.setField(field);
  889. detailDTO.setNumber(0L);
  890. detailDTO.setTopN(topN);
  891. countDetailDTOS.add(detailDTO);
  892. }
  893. } else if (countDetailDTOS.isEmpty()) {
  894. for (String value : values) {
  895. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  896. detailDTO.setName(value);
  897. detailDTO.setFirstName(firstName);
  898. detailDTO.setField(field);
  899. detailDTO.setNumber(0L);
  900. detailDTO.setTopN(topN);
  901. countDetailDTOS.add(detailDTO);
  902. }
  903. }
  904. map.put(firstName, countDetailDTOS);
  905. } else {
  906. detailDTOS.addAll(countDetailDTOS);
  907. }
  908. }
  909. }