EsCountService.java 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. package cn.cslg.pas.service.business.es;
  2. import cn.cslg.pas.common.dto.GetUnselectedDTO;
  3. import cn.cslg.pas.common.dto.business.EsCountDTO;
  4. import cn.cslg.pas.common.dto.business.EsCountDetailDTO;
  5. import cn.cslg.pas.common.dto.es.EsCustomFieldValueDTO;
  6. import cn.cslg.pas.common.dto.es.EsDateRangeDTO;
  7. import cn.cslg.pas.common.utils.parseQueryToTree.expressManager;
  8. import cn.cslg.pas.common.utils.parseQueryToTree.operateNode;
  9. import cn.cslg.pas.common.utils.parseQueryToTree.treeNode;
  10. import cn.cslg.pas.common.vo.EsConfigVO;
  11. import cn.cslg.pas.common.vo.business.EsAllCountVO;
  12. import cn.cslg.pas.common.vo.business.EsCountVO;
  13. import cn.cslg.pas.common.vo.es.EsDateRangeVO;
  14. import cn.cslg.pas.domain.es.Patent;
  15. import cn.cslg.pas.factorys.EsCountAnalyseBuilderFactory.EsCountAnalysisBuilderFactory;
  16. import cn.cslg.pas.factorys.EsCountAnalyseBuilderFactory.IEsCountAnalysisBuilder;
  17. import cn.cslg.pas.service.business.CommonService;
  18. import cn.cslg.pas.service.query.FormatQueryService;
  19. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  20. import co.elastic.clients.elasticsearch._types.aggregations.*;
  21. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  22. import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
  23. import co.elastic.clients.elasticsearch.core.SearchRequest;
  24. import co.elastic.clients.elasticsearch.core.SearchResponse;
  25. import co.elastic.clients.elasticsearch.core.search.Hit;
  26. import com.alibaba.fastjson.JSON;
  27. import lombok.RequiredArgsConstructor;
  28. import org.apache.commons.lang3.StringUtils;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.context.annotation.Lazy;
  31. import org.springframework.stereotype.Service;
  32. import org.springframework.util.CollectionUtils;
  33. import java.io.IOException;
  34. import java.text.ParseException;
  35. import java.text.SimpleDateFormat;
  36. import java.util.*;
  37. import java.util.concurrent.atomic.AtomicLong;
  38. import java.util.stream.Collectors;
  39. @Service
  40. @RequiredArgsConstructor(onConstructor_ = {@Lazy})
  41. public class EsCountService {
  42. private final List<String> childList = Arrays.asList("field");
  43. private final List<String> nestedList = Arrays.asList("PA", "IN", "PE", "SAT", "SRH","PRCO");
  44. private final List<String> dateList = Arrays.asList("PD", "AD", "GD");
  45. private final List<String> numberList = Arrays.asList("QPN", "QDPN", "SFN", "IFN", "PFN");
  46. private final List<String> nestDateList = Arrays.asList("PRD");
  47. private final List<String> nestChildList = Arrays.asList("MAT","MRH","MIN");
  48. private final ElasticsearchClient client;
  49. @Autowired
  50. private EsCountAnalysisBuilderFactory esCountAnalysisBuilderFactory;
  51. @Autowired
  52. private FormatQueryService formatQueryService;
  53. @Autowired
  54. private EsService esService;
  55. /**
  56. * 聚合统计
  57. *
  58. * @param vo
  59. * @return
  60. * @throws Exception
  61. */
  62. public EsCountDTO esCountAnalysis(EsAllCountVO vo) throws Exception {
  63. List<EsCountVO> countVOS = vo.getCountVOS();
  64. String searchCondition = vo.getCondition();
  65. List<EsCustomFieldValueDTO> customFields = vo.getCustomFields();
  66. Integer taskId = vo.getTaskId();
  67. Integer projectId = vo.getProjectId();
  68. EsCountDTO esCountDTO = new EsCountDTO();
  69. HashMap<String, List<EsCountDetailDTO>> map = new HashMap<>();
  70. List<EsCountDetailDTO> detailDTOS = new ArrayList<>();
  71. if (countVOS.size() > 1) {
  72. EsCountVO countVO = countVOS.get(0);
  73. List<String> values = countVO.getValues();
  74. values.removeIf(i -> i.equals("其他"));
  75. List<EsCountVO> esCountVOS = new ArrayList<>();
  76. esCountVOS.add(countVOS.get(1));
  77. if (StringUtils.isNotEmpty(countVO.getFieldId())) {
  78. if (!CollectionUtils.isEmpty(values)) {
  79. for (String value : values) {
  80. EsCustomFieldValueDTO valueDTO = new EsCustomFieldValueDTO();
  81. valueDTO.setFieldId(countVO.getFieldId());
  82. valueDTO.setFieldValue(Arrays.asList("\""+value+"\""));
  83. customFields.add(valueDTO);
  84. this.getReturnData(searchCondition, "",customFields, taskId, projectId,
  85. esCountVOS, detailDTOS, esCountDTO, value, map);
  86. }
  87. }
  88. } else {
  89. for (String value : values) {
  90. String condition = "";
  91. if (dateList.contains(countVO.getField())) {
  92. condition = this.getDateFormat(countVO.getField(), value);
  93. } else {
  94. condition = countVO.getField() + " = " + "\""+value+"\"";
  95. }
  96. this.getReturnData(searchCondition, condition, customFields, taskId, projectId,
  97. esCountVOS, detailDTOS, esCountDTO, value, map);
  98. }
  99. }
  100. } else {
  101. this.getReturnData(searchCondition, "", customFields, taskId, projectId, countVOS,
  102. detailDTOS, esCountDTO, "", map);
  103. }
  104. esCountDTO.setDetailDTOS(detailDTOS);
  105. return esCountDTO;
  106. }
  107. public void getReturnData(String searchCondition,String condition, List<EsCustomFieldValueDTO> customFields, Integer taskId,
  108. Integer projectId, List<EsCountVO> countVOS, List<EsCountDetailDTO> detailDTOS,
  109. EsCountDTO esCountDTO, String firstName, Map<String, List<EsCountDetailDTO>> map) throws Exception {
  110. if (StringUtils.isNotEmpty(condition)) {
  111. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  112. searchCondition = condition + " AND " + searchCondition;
  113. } else {
  114. searchCondition = condition;
  115. }
  116. }
  117. if (!CollectionUtils.isEmpty(customFields)) {
  118. searchCondition = esService.parseCustomField(customFields,projectId,taskId);
  119. }
  120. searchCondition = this.getCondition(searchCondition, taskId, projectId);
  121. SearchRequest.Builder builder = new SearchRequest.Builder();
  122. //设置查询索引
  123. builder.index("patent");
  124. Query query = null;
  125. if (StringUtils.isNotEmpty(searchCondition)) {
  126. //1. 解析检索条件
  127. treeNode tree = expressManager.getInstance().Parse(searchCondition, false);
  128. //格式化检索式
  129. //3. 从es中检索数据
  130. query = formatQueryService.EsQueryToQuery((operateNode) tree, "patent",projectId);
  131. }
  132. for (EsCountVO countVO : countVOS) {
  133. String field = countVO.getField();
  134. Integer topN = countVO.getTopN();
  135. String valueOne = countVO.getValueOne();
  136. String valueTwo = countVO.getValueTwo();
  137. Integer fieldType = null;
  138. String type = countVO.getFieldType();
  139. if (StringUtils.isNotEmpty(type) && type.equals("tree")) {
  140. fieldType = 6;
  141. }
  142. String format = countVO.getFormat();
  143. List<String> values = countVO.getValues();
  144. Aggregation aggregation = this.getAggregation(countVO, projectId, taskId);
  145. if (query != null) {
  146. Query finalQuery = query;
  147. Aggregation finalAggregation = aggregation;
  148. Aggregation filtersAgg = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  149. .filters(i -> i.array(Arrays.asList(finalQuery))).build())
  150. .aggregations(new HashMap() {{
  151. put("filters_agg", finalAggregation);
  152. }}).build();
  153. builder.aggregations("Agg", filtersAgg);
  154. } else {
  155. builder.aggregations("Agg", aggregation);
  156. }
  157. //解除最大条数限制
  158. builder.trackTotalHits(i -> i.enabled(true));
  159. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  160. Aggregate agg = response.aggregations().get("Agg");
  161. if (query != null) {
  162. String finalSearchCondition = searchCondition;
  163. if (StringUtils.isNotEmpty(field)) {
  164. List<FiltersBucket> filtersBuckets = agg.filters().buckets().array();
  165. if (dateList.contains(field)) {
  166. if (CollectionUtils.isEmpty(values)) {
  167. filtersBuckets.forEach(filtersBucket -> {
  168. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  169. try {
  170. this.getDateCountDTOS(filtersAgg, field, topN, format, detailDTOS, esCountDTO,valueOne,valueTwo);
  171. } catch (ParseException e) {
  172. e.printStackTrace();
  173. }
  174. });
  175. } else {
  176. filtersBuckets.forEach(filtersBucket -> {
  177. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  178. this.getDateAnalysisDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  179. });
  180. }
  181. } else if (nestedList.contains(field)) {
  182. filtersBuckets.forEach(filtersBucket -> {
  183. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  184. this.getNestedCountDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO,
  185. firstName, map, values,valueOne);
  186. if (!CollectionUtils.isEmpty(values)) {
  187. esCountDTO.setAllNumber(filtersAgg.nested().docCount());
  188. }
  189. });
  190. } else if (nestDateList.contains(field)) {
  191. if (CollectionUtils.isEmpty(values)) {
  192. filtersBuckets.forEach(filtersBucket -> {
  193. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  194. Aggregate termsAgg = filtersAgg.nested().aggregations().get("terms_agg");
  195. try {
  196. this.getDateCountDTOS(termsAgg, field, topN, format, detailDTOS, esCountDTO,valueOne,valueTwo);
  197. } catch (ParseException e) {
  198. e.printStackTrace();
  199. }
  200. });
  201. } else {
  202. filtersBuckets.forEach(filtersBucket -> {
  203. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  204. Aggregate termsAgg = filtersAgg.nested().aggregations().get("terms_agg");
  205. this.getDateAnalysisDTOS(termsAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  206. });
  207. }
  208. } else if (nestChildList.contains(field)) {
  209. filtersBuckets.forEach(filtersBucket -> {
  210. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  211. Aggregate childAgg = filtersAgg.children().aggregations().get("childAgg");
  212. this.getNestedCountDTOS(childAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  213. if (!CollectionUtils.isEmpty(values)) {
  214. esCountDTO.setAllNumber(childAgg.nested().docCount());
  215. }
  216. });
  217. } else if (childList.contains(field)) {
  218. if (CollectionUtils.isEmpty(values)) {
  219. Integer finalFieldType = fieldType;
  220. filtersBuckets.forEach(filtersBucket -> {
  221. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  222. try {
  223. this.getChildCountDTOS(filtersAgg, field, finalFieldType, topN, detailDTOS, esCountDTO,projectId,taskId);
  224. } catch (Exception e) {
  225. e.printStackTrace();
  226. }
  227. });
  228. } else {
  229. Integer finalFieldType1 = fieldType;
  230. filtersBuckets.forEach(filtersBucket -> {
  231. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  232. this.getChildAnalysisDTOS(filtersAgg, field, finalFieldType1, topN,
  233. detailDTOS, esCountDTO, firstName, map, values);
  234. });
  235. }
  236. } else if (numberList.contains(field)) {
  237. if (CollectionUtils.isEmpty(values)) {
  238. } else {
  239. filtersBuckets.forEach(filtersBucket -> {
  240. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  241. this.getNumberAnalysisDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  242. });
  243. }
  244. } else {
  245. filtersBuckets.forEach(filtersBucket -> {
  246. Aggregate filtersAgg = filtersBucket.aggregations().get("filters_agg");
  247. this.getTermCountDTOS(filtersAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  248. });
  249. }
  250. } else {
  251. this.getFilterCountDTO(agg, finalSearchCondition, detailDTOS);
  252. }
  253. } else {
  254. if (dateList.contains(field)) {
  255. if (CollectionUtils.isEmpty(values)) {
  256. this.getDateCountDTOS(agg, field, topN, format, detailDTOS, esCountDTO,valueOne,valueTwo);
  257. } else {
  258. this.getDateAnalysisDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  259. }
  260. } else if (nestedList.contains(field)) {
  261. this.getNestedCountDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  262. if (!CollectionUtils.isEmpty(values)) {
  263. esCountDTO.setAllNumber(agg.nested().docCount());
  264. }
  265. } else if (nestDateList.contains(field)) {
  266. Aggregate termsAgg = agg.nested().aggregations().get("terms_agg");
  267. this.getDateCountDTOS(termsAgg, field, topN, format, detailDTOS, esCountDTO,valueOne,valueTwo);
  268. } else if (nestChildList.contains(field)) {
  269. Aggregate childAgg = agg.children().aggregations().get("childAgg");
  270. this.getNestedCountDTOS(childAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  271. if (!CollectionUtils.isEmpty(values)) {
  272. esCountDTO.setAllNumber(childAgg.nested().docCount());
  273. }
  274. } else if (childList.contains(field)) {
  275. if (CollectionUtils.isEmpty(values)) {
  276. this.getChildCountDTOS(agg, field, fieldType, topN, detailDTOS, esCountDTO, projectId, taskId);
  277. } else {
  278. this.getChildAnalysisDTOS(agg, field, fieldType, topN,
  279. detailDTOS, esCountDTO, firstName, map, values);
  280. }
  281. } else if (numberList.contains(field)) {
  282. this.getNumberAnalysisDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  283. } else {
  284. this.getTermCountDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  285. }
  286. }
  287. esCountDTO.setCondition(searchCondition);
  288. esCountDTO.setAnalyseMap(map);
  289. }
  290. }
  291. public void getReturnData1(String searchCondition,String condition, List<EsCustomFieldValueDTO> customFields, Integer taskId,
  292. Integer projectId, List<EsCountVO> countVOS, List<EsCountDetailDTO> detailDTOS,
  293. EsCountDTO esCountDTO, String firstName, Map<String, List<EsCountDetailDTO>> map) throws Exception {
  294. if (StringUtils.isNotEmpty(condition)) {
  295. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  296. searchCondition = condition + " AND " + searchCondition;
  297. } else {
  298. searchCondition = condition;
  299. }
  300. }
  301. if (!CollectionUtils.isEmpty(customFields)) {
  302. searchCondition = esService.parseCustomField(customFields,projectId,taskId);
  303. }
  304. searchCondition = this.getCondition(searchCondition, taskId, projectId);
  305. SearchRequest.Builder builder = new SearchRequest.Builder();
  306. //设置查询索引
  307. builder.index("patent");
  308. Query query = null;
  309. if (StringUtils.isNotEmpty(searchCondition)) {
  310. //1. 解析检索条件
  311. treeNode tree = expressManager.getInstance().Parse(searchCondition, false);
  312. //格式化检索式
  313. //3. 从es中检索数据
  314. query = formatQueryService.EsQueryToQuery((operateNode) tree, "patent",projectId);
  315. builder.query(query);
  316. }
  317. for (EsCountVO countVO : countVOS) {
  318. String field = countVO.getField();
  319. Integer topN = countVO.getTopN();
  320. String valueOne = countVO.getValueOne();
  321. String valueTwo = countVO.getValueTwo();
  322. Integer fieldType = null;
  323. String type = countVO.getFieldType();
  324. if (StringUtils.isNotEmpty(type) && type.equals("tree")) {
  325. fieldType = 6;
  326. }
  327. String format = countVO.getFormat();
  328. List<String> values = countVO.getValues();
  329. Aggregation aggregation = this.getAggregation(countVO, projectId, taskId);
  330. builder.aggregations("Agg", aggregation);
  331. //解除最大条数限制
  332. builder.trackTotalHits(i -> i.enabled(true));
  333. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  334. Aggregate agg = response.aggregations().get("Agg");
  335. if (StringUtils.isNotEmpty(field)) {
  336. if (dateList.contains(field)) {
  337. if (CollectionUtils.isEmpty(values)) {
  338. this.getDateCountDTOS(agg, field, topN, format, detailDTOS, esCountDTO,valueOne,valueTwo);
  339. } else {
  340. this.getDateAnalysisDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  341. }
  342. } else if (nestedList.contains(field)) {
  343. this.getNestedCountDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  344. if (!CollectionUtils.isEmpty(values)) {
  345. esCountDTO.setAllNumber(agg.nested().docCount());
  346. }
  347. } else if (nestDateList.contains(field)) {
  348. if (CollectionUtils.isEmpty(values)) {
  349. Aggregate termsAgg = agg.nested().aggregations().get("terms_agg");
  350. this.getDateCountDTOS(termsAgg, field, topN, format, detailDTOS, esCountDTO,valueOne,valueTwo);
  351. } else {
  352. Aggregate termsAgg = agg.nested().aggregations().get("terms_agg");
  353. this.getDateAnalysisDTOS(termsAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  354. }
  355. } else if (nestChildList.contains(field)) {
  356. Aggregate childAgg = agg.children().aggregations().get("childAgg");
  357. this.getNestedCountDTOS(childAgg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  358. if (!CollectionUtils.isEmpty(values)) {
  359. esCountDTO.setAllNumber(childAgg.nested().docCount());
  360. }
  361. } else if (childList.contains(field)) {
  362. if (CollectionUtils.isEmpty(values)) {
  363. this.getChildCountDTOS(agg, field, fieldType, topN, detailDTOS, esCountDTO,projectId,taskId);
  364. } else {
  365. this.getChildAnalysisDTOS(agg, field, fieldType, topN,
  366. detailDTOS, esCountDTO, firstName, map, values);
  367. }
  368. } else if (numberList.contains(field)) {
  369. if (CollectionUtils.isEmpty(values)) {
  370. } else {
  371. this.getNumberAnalysisDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values);
  372. }
  373. } else {
  374. this.getTermCountDTOS(agg, field, topN, detailDTOS, esCountDTO, firstName, map, values,valueOne);
  375. }
  376. } else {
  377. this.getFilterCountDTO(agg, searchCondition, detailDTOS);
  378. }
  379. esCountDTO.setCondition(searchCondition);
  380. esCountDTO.setAnalyseMap(map);
  381. }
  382. }
  383. public EsDateRangeDTO getFieldRange(EsDateRangeVO rangeVO) throws Exception {
  384. String searchCondition = rangeVO.getCondition();
  385. String field = rangeVO.getField();
  386. List<EsCustomFieldValueDTO> customFields = rangeVO.getCustomFields();
  387. if (!CollectionUtils.isEmpty(customFields)) {
  388. searchCondition = esService.parseCustomField(customFields, rangeVO.getProjectId(), rangeVO.getTaskId());
  389. }
  390. Integer taskId = rangeVO.getTaskId();
  391. Integer projectId = rangeVO.getProjectId();
  392. searchCondition = this.getCondition(searchCondition, taskId, projectId);
  393. SearchRequest.Builder builder = new SearchRequest.Builder();
  394. //设置查询索引
  395. builder.index("patent");
  396. //设置查询索引
  397. Query query = null;
  398. if (StringUtils.isNotEmpty(searchCondition)) {
  399. //1. 解析检索条件
  400. treeNode tree = expressManager.getInstance().Parse(searchCondition, false);
  401. //格式化检索式
  402. //3. 从es中检索数据
  403. query = formatQueryService.EsQueryToQuery((operateNode) tree, "patent",projectId);
  404. }
  405. String esField = "";
  406. if (StringUtils.isNotEmpty(field)) {
  407. switch (field) {
  408. case "AD":
  409. esField = "app_date";
  410. break;
  411. case "PD":
  412. esField = "public_date";
  413. break;
  414. case "GD":
  415. esField = "grant_date";
  416. break;
  417. }
  418. }
  419. EsDateRangeDTO rangeDTO = new EsDateRangeDTO();
  420. if (StringUtils.isNotEmpty(esField)) {
  421. String finalEsField = esField;
  422. Query finalQuery = query;
  423. Aggregation min = AggregationBuilders.min(i -> i.field(finalEsField).format("yyyy"));
  424. Aggregation filtersAgg = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  425. .filters(i -> i.array(Arrays.asList(finalQuery))).build())
  426. .aggregations(new HashMap() {{
  427. put("filters_agg", min);
  428. }}).build();
  429. Aggregation max = AggregationBuilders.max(i -> i.field(finalEsField).format("yyyy"));
  430. Aggregation maxFilters = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  431. .filters(i -> i.array(Arrays.asList(finalQuery))).build())
  432. .aggregations(new HashMap() {{
  433. put("max_agg", max);
  434. }}).build();
  435. builder.aggregations("minAgg", filtersAgg);
  436. builder.aggregations("maxAgg", maxFilters);
  437. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  438. Aggregate minAgg = response.aggregations().get("minAgg");
  439. if (minAgg != null) {
  440. List<FiltersBucket> list = minAgg.filters().buckets().array();
  441. for (FiltersBucket bucket : list) {
  442. Aggregate aggregate = bucket.aggregations().get("filters_agg");
  443. String minValue = aggregate.min().valueAsString();
  444. rangeDTO.setMinDate(minValue);
  445. }
  446. }
  447. Aggregate maxAgg = response.aggregations().get("maxAgg");
  448. if (maxAgg != null) {
  449. List<FiltersBucket> list = maxAgg.filters().buckets().array();
  450. for (FiltersBucket bucket : list) {
  451. Aggregate aggregate = bucket.aggregations().get("max_agg");
  452. String maxValue = aggregate.max().valueAsString();
  453. rangeDTO.setMaxDate(maxValue);
  454. }
  455. }
  456. }
  457. return rangeDTO;
  458. }
  459. /**
  460. * 查询共用Aggregation
  461. *
  462. * @param countVO
  463. * @return
  464. * @throws Exception
  465. */
  466. public Aggregation getAggregation(EsCountVO countVO, Integer projectId, Integer taskId) throws Exception {
  467. String field = countVO.getField();
  468. Integer topN = countVO.getTopN();
  469. Boolean ifHaveChild = countVO.getIfHaveChild();
  470. String fieldId = countVO.getFieldId();
  471. Integer fieldType = null;
  472. String type = countVO.getFieldType();
  473. if (StringUtils.isNotEmpty(type) && type.equals("tree")) {
  474. fieldType = 6;
  475. }
  476. String format = countVO.getFormat();
  477. String valueOne = countVO.getValueOne();
  478. String valueTwo = countVO.getValueTwo();
  479. List<String> values = countVO.getValues();
  480. IEsCountAnalysisBuilder iEsCountAnalysisBuilder = null;
  481. String json = CommonService.readJsonFile("esCountAnalysis.json");
  482. List<EsConfigVO> esConfigVOS = JSON.parseArray(json, EsConfigVO.class);
  483. EsConfigVO esConfigVO = esConfigVOS.stream().filter(item -> item.getField().equals(field))
  484. .findFirst().orElse(null);
  485. Aggregation aggregation = null;
  486. if (esConfigVO != null) {
  487. iEsCountAnalysisBuilder = esCountAnalysisBuilderFactory.getClass(esConfigVO.getEsClass());
  488. iEsCountAnalysisBuilder.setField(esConfigVO.getEsField());
  489. iEsCountAnalysisBuilder.setValueOne(valueOne);
  490. iEsCountAnalysisBuilder.setValueTwo(valueTwo);
  491. iEsCountAnalysisBuilder.setValues(values);
  492. iEsCountAnalysisBuilder.setFieldId(fieldId);
  493. iEsCountAnalysisBuilder.setFieldType(String.valueOf(fieldType));
  494. iEsCountAnalysisBuilder.setTopN(topN);
  495. iEsCountAnalysisBuilder.setFormat(format);
  496. iEsCountAnalysisBuilder.setProjectId(projectId);
  497. iEsCountAnalysisBuilder.setTaskId(taskId);
  498. iEsCountAnalysisBuilder.setIfHaveChild(ifHaveChild);
  499. if (iEsCountAnalysisBuilder.getField().contains(".")) {
  500. String path = iEsCountAnalysisBuilder.getField()
  501. .substring(0, iEsCountAnalysisBuilder.getField().indexOf("."));
  502. iEsCountAnalysisBuilder.setPath(path);
  503. }
  504. aggregation = iEsCountAnalysisBuilder.createCountAnalyseAgg();
  505. }
  506. return aggregation;
  507. }
  508. /**
  509. * 获取筛选条件
  510. *
  511. * @param taskId
  512. * @param projectId
  513. * @return
  514. */
  515. public String getCondition(String searchCondition, Integer taskId, Integer projectId) {
  516. if (taskId != null) {
  517. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  518. searchCondition = "taskId = " + taskId + " AND " + searchCondition;
  519. } else {
  520. searchCondition = "taskId = " + taskId;
  521. }
  522. } else {
  523. if (projectId != null) {
  524. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  525. searchCondition = "projectId = " + projectId + " AND " + searchCondition;
  526. } else {
  527. searchCondition = "projectId = " + projectId;
  528. }
  529. }
  530. }
  531. return searchCondition;
  532. }
  533. /**
  534. * 获取Filter聚合返回数据
  535. *
  536. * @param agg
  537. * @param condition
  538. * @return
  539. */
  540. public void getFilterCountDTO(Aggregate agg, String condition, List<EsCountDetailDTO> detailDTOS) {
  541. EsCountDetailDTO filterDTO = new EsCountDetailDTO();
  542. filterDTO.setField("condition");
  543. filterDTO.setName(condition);
  544. filterDTO.setNumber(agg.filter().docCount());
  545. if (filterDTO.getNumber() > 0) {
  546. detailDTOS.add(filterDTO);
  547. }
  548. }
  549. /**
  550. * 获取Terms聚合后数据
  551. *
  552. * @param agg
  553. * @param field
  554. * @param detailDTOS
  555. */
  556. public void getTermCountDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  557. EsCountDTO esCountDTO, String firstName,
  558. Map<String, List<EsCountDetailDTO>> map,List<String> values,String valueOne) {
  559. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  560. long otherNum = 0l;
  561. if (StringUtils.isNotEmpty(valueOne)) {
  562. Aggregate filterAgg = agg.filter().aggregations().get("filter_agg");
  563. List<StringTermsBucket> list = filterAgg.sterms().buckets().array();
  564. for (StringTermsBucket bucket : list) {
  565. EsCountDetailDTO dto = new EsCountDetailDTO();
  566. dto.setField(field);
  567. String value = bucket.key().stringValue();
  568. if (StringUtils.isNotEmpty(value)) {
  569. dto.setName(value);
  570. dto.setNumber(bucket.docCount());
  571. dto.setTopN(topN);
  572. dto.setFirstName(firstName);
  573. if (dto.getNumber() > 0) {
  574. countDetailDTOS.add(dto);
  575. }
  576. } else {
  577. otherNum += 1;
  578. }
  579. }
  580. if (countDetailDTOS.size() > topN) {
  581. countDetailDTOS.remove(countDetailDTOS.size() - 1);
  582. }
  583. EsCountDetailDTO countDTO = new EsCountDetailDTO();
  584. countDTO.setField(field);
  585. countDTO.setName("其他");
  586. countDTO.setTopN(topN);
  587. Long count = filterAgg.sterms().sumOtherDocCount();
  588. if (count > 0) {
  589. countDTO.setNumber(count + otherNum);
  590. countDetailDTOS.add(countDTO);
  591. }
  592. esCountDTO.setRemainingNum(count);
  593. } else {
  594. List<StringTermsBucket> list = agg.sterms().buckets().array();
  595. for (StringTermsBucket bucket : list) {
  596. EsCountDetailDTO dto = new EsCountDetailDTO();
  597. dto.setField(field);
  598. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  599. String value = bucket.key().stringValue();
  600. if (StringUtils.isNotEmpty(value)) {
  601. dto.setName(value);
  602. dto.setNumber(bucket.docCount());
  603. dto.setTopN(topN);
  604. dto.setFirstName(firstName);
  605. if (aggregate != null) {
  606. dto.setNumber(aggregate.filter().docCount());
  607. }
  608. if (dto.getNumber() > 0) {
  609. countDetailDTOS.add(dto);
  610. }
  611. } else {
  612. otherNum += 1;
  613. }
  614. }
  615. if (countDetailDTOS.size() > topN) {
  616. countDetailDTOS.remove(countDetailDTOS.size() - 1);
  617. }
  618. EsCountDetailDTO countDTO = new EsCountDetailDTO();
  619. countDTO.setField(field);
  620. countDTO.setName("其他");
  621. countDTO.setTopN(topN);
  622. Long count = agg.sterms().sumOtherDocCount();
  623. if (count > 0) {
  624. countDTO.setNumber(count + otherNum);
  625. detailDTOS.add(countDTO);
  626. }
  627. esCountDTO.setRemainingNum(count);
  628. }
  629. List<String> strs = new ArrayList<>();
  630. if (!CollectionUtils.isEmpty(values)) {
  631. strs.addAll(values);
  632. }
  633. if (StringUtils.isNotEmpty(firstName)) {
  634. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  635. if (countDetailDTOS.size() != values.size()) {
  636. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  637. strs.removeIf(i -> i.equals(detailDTO.getName()));
  638. }
  639. for (String value : strs) {
  640. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  641. detailDTO.setName(value);
  642. detailDTO.setFirstName(firstName);
  643. detailDTO.setField(field);
  644. detailDTO.setNumber(0L);
  645. detailDTO.setTopN(topN);
  646. countDetailDTOS.add(detailDTO);
  647. }
  648. } else if (countDetailDTOS.isEmpty()) {
  649. for (String value : values) {
  650. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  651. detailDTO.setName(value);
  652. detailDTO.setFirstName(firstName);
  653. detailDTO.setField(field);
  654. detailDTO.setNumber(0L);
  655. detailDTO.setTopN(topN);
  656. countDetailDTOS.add(detailDTO);
  657. }
  658. }
  659. map.put(firstName, countDetailDTOS);
  660. } else {
  661. detailDTOS.addAll(countDetailDTOS);
  662. }
  663. }
  664. /**
  665. * 获取children聚合后数据
  666. *
  667. * @param agg
  668. * @param field
  669. * @param detailDTOS
  670. */
  671. public void getChildCountDTOS(Aggregate agg, String field, Integer fieldType, Integer topN,
  672. List<EsCountDetailDTO> detailDTOS, EsCountDTO esCountDTO,Integer projectId, Integer taskId) throws Exception {
  673. esCountDTO.setAllNumber(agg.children().docCount());
  674. Aggregate childAgg = agg.children().aggregations().get("childAgg");
  675. List<StringTermsBucket> list = childAgg.sterms().buckets().array();
  676. list.forEach(bucket -> {
  677. Aggregate aggregate = bucket.aggregations().get("termAgg");
  678. List<StringTermsBucket> termsBuckets = aggregate.sterms().buckets().array();
  679. termsBuckets.forEach(termsBucket -> {
  680. Aggregate termAgg = termsBucket.aggregations().get("filterAgg");
  681. long count = termAgg.filter().docCount();
  682. if (count > 0) {
  683. EsCountDetailDTO dto = new EsCountDetailDTO();
  684. dto.setField(field);
  685. dto.setName(termsBucket.key().stringValue());
  686. dto.setNumber(termsBucket.docCount());
  687. dto.setNumber(count);
  688. dto.setTopN(topN);
  689. if (dto.getNumber() > 0) {
  690. detailDTOS.add(dto);
  691. }
  692. }
  693. });
  694. });
  695. if (fieldType == null || fieldType != 6) {
  696. GetUnselectedDTO unselectedDTO = this.getUnselectedCustomNum(projectId, taskId);
  697. EsCountDetailDTO detail = new EsCountDetailDTO();
  698. detail.setField(field);
  699. detail.setName("未选择");
  700. detail.setNumber(unselectedDTO.getNumber().longValue());
  701. detail.setTopN(topN);
  702. if (!detailDTOS.contains(detail)) {
  703. detailDTOS.add(detail);
  704. }
  705. }
  706. }
  707. public GetUnselectedDTO getUnselectedCustomNum(Integer projectId, Integer taskId) throws Exception {
  708. GetUnselectedDTO dto = new GetUnselectedDTO();
  709. SearchRequest.Builder builder = new SearchRequest.Builder();
  710. //设置查询索引
  711. builder.index("patent");
  712. Query q = null;
  713. if (taskId != null) {
  714. Query query = QueryBuilders.term(i -> i.field("project_task.task_id").value(taskId));
  715. q = QueryBuilders.hasChild(i -> i.type("task").query(query));
  716. } else {
  717. Query query = QueryBuilders.term(i -> i.field("project_id").value(projectId));
  718. q = QueryBuilders.hasChild(i -> i.type("project").query(query));
  719. }
  720. builder.size(9999);
  721. builder.query(q);
  722. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  723. List<Hit<Patent>> hits = response.hits().hits();
  724. List<String> list = new ArrayList<>();
  725. for (Hit<Patent> hit : hits) {
  726. String id = hit.id();
  727. list.add(id);
  728. }
  729. if (!CollectionUtils.isEmpty(list)) {
  730. dto = this.ifExistChild(list);
  731. }
  732. return dto;
  733. }
  734. public GetUnselectedDTO ifExistChild(List<String> list) throws IOException {
  735. GetUnselectedDTO dto = new GetUnselectedDTO();
  736. List<String> existChildIds = new ArrayList<>();
  737. List<String> beinglessChildIds = new ArrayList<>();
  738. int count = 0;
  739. for (String id : list) {
  740. SearchRequest.Builder builder = new SearchRequest.Builder();
  741. //设置查询索引
  742. builder.index("patent");
  743. Query q1 = QueryBuilders.parentId(i -> i.type("project_customfield").id(id));
  744. Query q2 = QueryBuilders.exists(i -> i.field("custom_field"));
  745. Query bool = QueryBuilders.bool(i -> i.must(q1, q2));
  746. builder.query(bool);
  747. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  748. Long total = response.hits().total().value();
  749. if (total > 0) {
  750. existChildIds.add(id);
  751. } else {
  752. beinglessChildIds.add(id);
  753. count++;
  754. }
  755. }
  756. dto.setNumber(count);
  757. dto.setExistChildIds(existChildIds);
  758. dto.setBeinglessChildIds(beinglessChildIds);
  759. return dto;
  760. }
  761. /**
  762. * 获取children分析后数据
  763. *
  764. * @param agg
  765. * @param field
  766. * @param detailDTOS
  767. */
  768. public void getChildAnalysisDTOS(Aggregate agg, String field, Integer fieldType, Integer topN,
  769. List<EsCountDetailDTO> detailDTOS, EsCountDTO esCountDTO,
  770. String firstName, Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  771. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  772. Aggregate childAgg = agg.children().aggregations().get("childAgg");
  773. List<StringTermsBucket> list = childAgg.sterms().buckets().array();
  774. list.forEach(bucket -> {
  775. esCountDTO.setAllNumber(bucket.docCount());
  776. Aggregate aggregate = bucket.aggregations().get("termAgg");
  777. List<StringTermsBucket> termsBuckets = aggregate.sterms().buckets().array();
  778. termsBuckets.forEach(termsBucket -> {
  779. EsCountDetailDTO dto = new EsCountDetailDTO();
  780. dto.setField(field);
  781. dto.setName(termsBucket.key().stringValue());
  782. dto.setNumber(termsBucket.docCount());
  783. dto.setFirstName(firstName);
  784. dto.setTopN(topN);
  785. countDetailDTOS.add(dto);
  786. if (fieldType == null || fieldType != 6) {
  787. Long docCount = aggregate.sterms().sumOtherDocCount();
  788. EsCountDetailDTO detail = new EsCountDetailDTO();
  789. detail.setField(field);
  790. detail.setName("未选择");
  791. detail.setNumber(docCount);
  792. detail.setTopN(topN);
  793. if (!countDetailDTOS.contains(detail)) {
  794. countDetailDTOS.add(detail);
  795. }
  796. }
  797. });
  798. });
  799. List<String> strs = new ArrayList<>();
  800. if (!CollectionUtils.isEmpty(values)) {
  801. strs.addAll(values);
  802. }
  803. if (StringUtils.isNotEmpty(firstName)) {
  804. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  805. if (countDetailDTOS.size() != values.size()) {
  806. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  807. strs.removeIf(i -> i.equals(detailDTO.getName()));
  808. }
  809. for (String value : strs) {
  810. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  811. detailDTO.setName(value);
  812. detailDTO.setFirstName(firstName);
  813. detailDTO.setField(field);
  814. detailDTO.setNumber(0L);
  815. detailDTO.setTopN(topN);
  816. countDetailDTOS.add(detailDTO);
  817. }
  818. } else if (countDetailDTOS.isEmpty()) {
  819. for (String value : values) {
  820. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  821. detailDTO.setName(value);
  822. detailDTO.setFirstName(firstName);
  823. detailDTO.setField(field);
  824. detailDTO.setNumber(0L);
  825. detailDTO.setTopN(topN);
  826. countDetailDTOS.add(detailDTO);
  827. }
  828. }
  829. map.put(firstName, countDetailDTOS);
  830. } else {
  831. detailDTOS.addAll(countDetailDTOS);
  832. }
  833. }
  834. /**
  835. * 获取range分析后数据
  836. *
  837. * @param agg
  838. * @param field
  839. * @param detailDTOS
  840. */
  841. public void getNumberAnalysisDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  842. EsCountDTO esCountDTO, String firstName,
  843. Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  844. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  845. List<RangeBucket> list = agg.range().buckets().array();
  846. for (RangeBucket bucket : list) {
  847. EsCountDetailDTO dto = new EsCountDetailDTO();
  848. dto.setField(field);
  849. dto.setName(bucket.key());
  850. dto.setNumber(bucket.docCount());
  851. dto.setTopN(topN);
  852. dto.setFirstName(firstName);
  853. countDetailDTOS.add(dto);
  854. // if (dto.getNumber() > 0) {
  855. // detailDTOS.add(dto);
  856. // }
  857. }
  858. List<String> strs = new ArrayList<>();
  859. if (!CollectionUtils.isEmpty(values)) {
  860. strs.addAll(values);
  861. }
  862. if (StringUtils.isNotEmpty(firstName)) {
  863. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  864. if (countDetailDTOS.size() != values.size()) {
  865. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  866. strs.removeIf(i -> i.equals(detailDTO.getName()));
  867. }
  868. for (String value : strs) {
  869. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  870. detailDTO.setName(value);
  871. detailDTO.setFirstName(firstName);
  872. detailDTO.setField(field);
  873. detailDTO.setNumber(0L);
  874. detailDTO.setTopN(topN);
  875. countDetailDTOS.add(detailDTO);
  876. }
  877. } else if (countDetailDTOS.isEmpty()) {
  878. for (String value : values) {
  879. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  880. detailDTO.setName(value);
  881. detailDTO.setFirstName(firstName);
  882. detailDTO.setField(field);
  883. detailDTO.setNumber(0L);
  884. detailDTO.setTopN(topN);
  885. countDetailDTOS.add(detailDTO);
  886. }
  887. }
  888. map.put(firstName, countDetailDTOS);
  889. } else {
  890. detailDTOS.addAll(countDetailDTOS);
  891. }
  892. }
  893. /**
  894. * 获取dateHistogram聚合后数据
  895. *
  896. * @param agg
  897. * @param field
  898. * @param detailDTOS
  899. */
  900. public void getDateCountDTOS(Aggregate agg, String field, Integer topN, String format, List<EsCountDetailDTO> detailDTOS,
  901. EsCountDTO esCountDTO, String valueOne, String valueTwo) throws ParseException {
  902. List<DateHistogramBucket> list = agg.dateHistogram().buckets().array();
  903. long all = Long.valueOf(String.valueOf(list.size()));
  904. esCountDTO.setAllNumber(all);
  905. List<EsCountDetailDTO> esCountDetailDTOS = new ArrayList<>();
  906. if (StringUtils.isNotEmpty(format) && format.equals("半年")) {
  907. List<EsCountDetailDTO> detailDTOList = new ArrayList<>();
  908. for (DateHistogramBucket bucket : list) {
  909. String year = bucket.keyAsString();
  910. SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
  911. String startMonth = year + "-01";
  912. Calendar calendar = Calendar.getInstance();
  913. Date date = monthFormat.parse(startMonth);
  914. calendar.setTime(date);
  915. calendar.add(Calendar.MONTH, 6);
  916. Date halfYearDate = calendar.getTime();
  917. Aggregate aggregate = bucket.aggregations().get("halfYearAgg");
  918. List<DateHistogramBucket> buckets = aggregate.dateHistogram().buckets().array();
  919. long h1Count = 0;
  920. long h2Count = 0;
  921. for (DateHistogramBucket histogramBucket : buckets) {
  922. String key = histogramBucket.keyAsString();
  923. Date month = monthFormat.parse(key);
  924. EsCountDetailDTO dto = new EsCountDetailDTO();
  925. dto.setField(field);
  926. dto.setName(year + "-H1");
  927. dto.setNumber(h1Count);
  928. dto.setTopN(topN);
  929. EsCountDetailDTO dto2 = new EsCountDetailDTO();
  930. dto2.setField(field);
  931. dto2.setName(year + "-H2");
  932. dto2.setNumber(h2Count);
  933. dto2.setTopN(topN);
  934. if (month.before(halfYearDate)) {
  935. h1Count += histogramBucket.docCount();
  936. dto.setNumber(h1Count);
  937. }
  938. if (month.after(halfYearDate)) {
  939. h2Count += histogramBucket.docCount();
  940. dto2.setNumber(h2Count);
  941. }
  942. detailDTOList.add(dto);
  943. detailDTOList.add(dto2);
  944. }
  945. }
  946. Map<String, List<EsCountDetailDTO>> map = detailDTOList.stream().collect(Collectors.groupingBy(EsCountDetailDTO::getName));
  947. for (String key : map.keySet()) {
  948. List<EsCountDetailDTO> dtoList = map.get(key);
  949. long sum = dtoList.stream().mapToLong(EsCountDetailDTO::getNumber).sum();
  950. EsCountDetailDTO detailDTO = dtoList.get(0);
  951. detailDTO.setNumber(sum);
  952. esCountDetailDTOS.add(detailDTO);
  953. }
  954. } else if (StringUtils.isNotEmpty(format) && format.equals("季")) {
  955. for (DateHistogramBucket bucket : list) {
  956. String yearMonth = bucket.keyAsString();
  957. String year = yearMonth.substring(0, yearMonth.indexOf("-"));
  958. String firstQuarter = year + "-01";
  959. String secondQuarter = year + "-04";
  960. String thirdQuarter = year + "-07";
  961. String forthQuarter = year + "-10";
  962. String firstQ = year + "-Q1";
  963. String secondQ = year + "-Q2";
  964. String thirdQ = year + "-Q3";
  965. String forthQ = year + "-Q4";
  966. EsCountDetailDTO dto = new EsCountDetailDTO();
  967. dto.setField(field);
  968. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  969. if (yearMonth.equals(firstQuarter)) {
  970. dto.setName(firstQ);
  971. } else if (yearMonth.equals(secondQuarter)) {
  972. dto.setName(secondQ);
  973. } else if (yearMonth.equals(thirdQuarter)) {
  974. dto.setName(thirdQ);
  975. } else if (yearMonth.equals(forthQuarter)) {
  976. dto.setName(forthQ);
  977. }
  978. dto.setNumber(bucket.docCount());
  979. dto.setTopN(topN);
  980. if (aggregate != null) {
  981. dto.setNumber(aggregate.filter().docCount());
  982. }
  983. esCountDetailDTOS.add(dto);
  984. }
  985. } else {
  986. list.forEach(bucket -> {
  987. EsCountDetailDTO dto = new EsCountDetailDTO();
  988. dto.setField(field);
  989. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  990. dto.setName(bucket.keyAsString());
  991. dto.setNumber(bucket.docCount());
  992. dto.setTopN(topN);
  993. if (aggregate != null) {
  994. dto.setNumber(aggregate.filter().docCount());
  995. }
  996. if (StringUtils.isNotEmpty(valueOne) || StringUtils.isNotEmpty(valueTwo)) {
  997. if (dto.getNumber() > 0) {
  998. esCountDetailDTOS.add(dto);
  999. }
  1000. } else {
  1001. esCountDetailDTOS.add(dto);
  1002. }
  1003. });
  1004. }
  1005. if (!CollectionUtils.isEmpty(esCountDetailDTOS)) {
  1006. if (StringUtils.isNotEmpty(valueOne) || StringUtils.isNotEmpty(valueTwo)) {
  1007. all = Long.valueOf(String.valueOf(esCountDetailDTOS.size()));
  1008. }
  1009. long num = Long.valueOf(String.valueOf(topN));
  1010. long finalNum = all - num;
  1011. if (finalNum > 0) {
  1012. esCountDTO.setRemainingNum(finalNum);
  1013. } else {
  1014. esCountDTO.setRemainingNum(0l);
  1015. }
  1016. List<EsCountDetailDTO> collect = esCountDetailDTOS.stream()
  1017. .sorted(Comparator.comparing(EsCountDetailDTO::getName).reversed()).limit(topN).collect(Collectors.toList());
  1018. detailDTOS.addAll(collect);
  1019. }
  1020. }
  1021. /**
  1022. * 获取dateHistogram分析后数据
  1023. *
  1024. * @param agg
  1025. * @param field
  1026. * @param topN
  1027. * @param detailDTOS
  1028. */
  1029. public void getDateAnalysisDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  1030. EsCountDTO esCountDTO, String firstName,
  1031. Map<String, List<EsCountDetailDTO>> map,List<String> values) {
  1032. List<RangeBucket> list1 = agg.dateRange().buckets().array();
  1033. List<EsCountDetailDTO> esCountDetailDTOS = new ArrayList<>();
  1034. for (RangeBucket bucket : list1) {
  1035. EsCountDetailDTO dto = new EsCountDetailDTO();
  1036. dto.setFirstName(firstName);
  1037. dto.setField(field);
  1038. dto.setName(bucket.key());
  1039. dto.setNumber(bucket.docCount());
  1040. dto.setTopN(topN);
  1041. esCountDetailDTOS.add(dto);
  1042. }
  1043. if (!CollectionUtils.isEmpty(esCountDetailDTOS)) {
  1044. List<EsCountDetailDTO> collect = esCountDetailDTOS.stream()
  1045. .sorted(Comparator.comparing(EsCountDetailDTO::getName).reversed()).limit(topN).collect(Collectors.toList());
  1046. List<String> strs = new ArrayList<>();
  1047. if (!CollectionUtils.isEmpty(values)) {
  1048. strs.addAll(values);
  1049. }
  1050. if (StringUtils.isNotEmpty(firstName)) {
  1051. collect.removeIf(dto -> dto.getName().equals("其他"));
  1052. if (collect.size() != values.size()) {
  1053. for (EsCountDetailDTO detailDTO : collect) {
  1054. strs.removeIf(i -> i.equals(detailDTO.getName()));
  1055. }
  1056. for (String value : strs) {
  1057. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  1058. detailDTO.setName(value);
  1059. detailDTO.setFirstName(firstName);
  1060. detailDTO.setField(field);
  1061. detailDTO.setNumber(0L);
  1062. detailDTO.setTopN(topN);
  1063. collect.add(detailDTO);
  1064. }
  1065. } else if (collect.isEmpty()) {
  1066. for (String value : values) {
  1067. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  1068. detailDTO.setName(value);
  1069. detailDTO.setFirstName(firstName);
  1070. detailDTO.setField(field);
  1071. detailDTO.setNumber(0L);
  1072. detailDTO.setTopN(topN);
  1073. collect.add(detailDTO);
  1074. }
  1075. }
  1076. map.put(firstName, collect);
  1077. } else {
  1078. detailDTOS.addAll(collect);
  1079. }
  1080. }
  1081. }
  1082. /**
  1083. * 获取nested聚合后数据
  1084. *
  1085. * @param agg
  1086. * @param field
  1087. * @param detailDTOS
  1088. */
  1089. public void getNestedCountDTOS(Aggregate agg, String field, Integer topN, List<EsCountDetailDTO> detailDTOS,
  1090. EsCountDTO esCountDTO, String firstName,
  1091. Map<String, List<EsCountDetailDTO>> map, List<String> values,String valueOne) {
  1092. Aggregate termsAgg = agg.nested().aggregations().get("terms_agg");
  1093. List<EsCountDetailDTO> countDetailDTOS = new ArrayList<>();
  1094. long otherNum = 0l;
  1095. if (StringUtils.isNotEmpty(valueOne)) {
  1096. Aggregate filterAgg = termsAgg.filter().aggregations().get("filter_agg");
  1097. List<StringTermsBucket> list = filterAgg.sterms().buckets().array();
  1098. for (StringTermsBucket bucket : list) {
  1099. EsCountDetailDTO dto = new EsCountDetailDTO();
  1100. dto.setField(field);
  1101. String value = bucket.key().stringValue();
  1102. if (StringUtils.isNotEmpty(value)) {
  1103. dto.setName(value);
  1104. dto.setNumber(bucket.docCount());
  1105. dto.setTopN(topN);
  1106. dto.setFirstName(firstName);
  1107. if (dto.getNumber() > 0) {
  1108. countDetailDTOS.add(dto);
  1109. }
  1110. } else {
  1111. otherNum += 1;
  1112. }
  1113. }
  1114. if (countDetailDTOS.size() > topN) {
  1115. countDetailDTOS.remove(countDetailDTOS.size() - 1);
  1116. }
  1117. EsCountDetailDTO countDTO = new EsCountDetailDTO();
  1118. countDTO.setField(field);
  1119. countDTO.setName("其他");
  1120. countDTO.setTopN(topN);
  1121. Long count = filterAgg.sterms().sumOtherDocCount();
  1122. if (count > 0) {
  1123. countDTO.setNumber(count + otherNum);
  1124. countDetailDTOS.add(countDTO);
  1125. }
  1126. esCountDTO.setRemainingNum(count);
  1127. } else {
  1128. List<StringTermsBucket> list = termsAgg.sterms().buckets().array();
  1129. for (StringTermsBucket bucket : list) {
  1130. EsCountDetailDTO dto = new EsCountDetailDTO();
  1131. dto.setField(field);
  1132. Aggregate aggregate = bucket.aggregations().get("filter_agg");
  1133. String value = bucket.key().stringValue();
  1134. if (StringUtils.isNotEmpty(value)) {
  1135. dto.setName(value);
  1136. dto.setNumber(bucket.docCount());
  1137. dto.setTopN(topN);
  1138. dto.setFirstName(firstName);
  1139. if (aggregate != null) {
  1140. dto.setNumber(aggregate.filter().docCount());
  1141. }
  1142. if (dto.getNumber() > 0) {
  1143. countDetailDTOS.add(dto);
  1144. }
  1145. } else {
  1146. otherNum += 1;
  1147. }
  1148. }
  1149. if (countDetailDTOS.size() > topN) {
  1150. countDetailDTOS.remove(countDetailDTOS.size() - 1);
  1151. }
  1152. EsCountDetailDTO countDTO = new EsCountDetailDTO();
  1153. countDTO.setField(field);
  1154. countDTO.setName("其他");
  1155. countDTO.setTopN(topN);
  1156. Long count = termsAgg.sterms().sumOtherDocCount();
  1157. if (count > 0) {
  1158. countDTO.setNumber(count + otherNum);
  1159. countDetailDTOS.add(countDTO);
  1160. }
  1161. esCountDTO.setRemainingNum(count);
  1162. }
  1163. List<String> strs = new ArrayList<>();
  1164. if (!CollectionUtils.isEmpty(values)) {
  1165. strs.addAll(values);
  1166. }
  1167. if (StringUtils.isNotEmpty(firstName)) {
  1168. countDetailDTOS.removeIf(dto -> dto.getName().equals("其他"));
  1169. if (countDetailDTOS.size() != values.size()) {
  1170. for (EsCountDetailDTO detailDTO : countDetailDTOS) {
  1171. strs.removeIf(i -> i.equals(detailDTO.getName()));
  1172. }
  1173. for (String value : strs) {
  1174. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  1175. detailDTO.setName(value);
  1176. detailDTO.setFirstName(firstName);
  1177. detailDTO.setField(field);
  1178. detailDTO.setNumber(0L);
  1179. detailDTO.setTopN(topN);
  1180. countDetailDTOS.add(detailDTO);
  1181. }
  1182. } else if (countDetailDTOS.isEmpty()) {
  1183. for (String value : values) {
  1184. EsCountDetailDTO detailDTO = new EsCountDetailDTO();
  1185. detailDTO.setName(value);
  1186. detailDTO.setFirstName(firstName);
  1187. detailDTO.setField(field);
  1188. detailDTO.setNumber(0L);
  1189. detailDTO.setTopN(topN);
  1190. countDetailDTOS.add(detailDTO);
  1191. }
  1192. }
  1193. map.put(firstName, countDetailDTOS);
  1194. } else {
  1195. detailDTOS.addAll(countDetailDTOS);
  1196. }
  1197. }
  1198. public String getDateFormat(String field,String value) {
  1199. String condition = "";
  1200. if (value.contains("Q") || value.contains("H") || value.length() == 9) {
  1201. String year = value.substring(0, value.indexOf("-"));
  1202. int nextYear = Integer.parseInt(year) + 1;
  1203. String start = "";
  1204. String end = "";
  1205. if (value.contains("Q1")) {
  1206. start = year + "-01";
  1207. end = year + "-04";
  1208. } else if (value.contains("Q2")) {
  1209. start = year + "-04";
  1210. end = year + "-07";
  1211. } else if (value.contains("Q3")) {
  1212. start = year + "-07";
  1213. end = year + "-10";
  1214. } else if (value.contains("Q4")) {
  1215. start = year + "-10";
  1216. end = nextYear + "-01";
  1217. } else if (value.contains("H1")) {
  1218. start = year + "-01";
  1219. end = year + "-07";
  1220. } else if (value.contains("H2")) {
  1221. start = year + "-07";
  1222. end = nextYear + "-01";
  1223. } else if (value.length() == 9) {
  1224. start = year;
  1225. end = value.substring(value.indexOf("-") + 1);
  1226. }
  1227. condition = field + ">=" + start + " " + "AND" + " " + field + "<" + end;
  1228. } else {
  1229. condition = field + " = " + value;
  1230. }
  1231. return condition;
  1232. }
  1233. }