EsService.java 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  1. package cn.cslg.pas.service.business.es;
  2. import cn.cslg.pas.common.core.base.IfConstant;
  3. import cn.cslg.pas.common.dto.GetUnselectedDTO;
  4. import cn.cslg.pas.common.dto.PatentColumnDTO;
  5. import cn.cslg.pas.common.dto.PatentDTO;
  6. import cn.cslg.pas.common.dto.business.EsPatentFamilyDTO;
  7. import cn.cslg.pas.common.dto.business.SelectClaimDTO;
  8. import cn.cslg.pas.common.dto.es.EsCustomFieldValueDTO;
  9. import cn.cslg.pas.common.model.request.MapRequest;
  10. import cn.cslg.pas.common.model.request.OrderDTO;
  11. import cn.cslg.pas.common.model.request.QueryRequest;
  12. import cn.cslg.pas.common.model.request.StringRequest;
  13. import cn.cslg.pas.common.utils.FormatUtil;
  14. import cn.cslg.pas.common.vo.*;
  15. import cn.cslg.pas.common.vo.es.EsCustomFieldBatchVO;
  16. import cn.cslg.pas.common.vo.es.EsPatentCommonVO;
  17. import cn.cslg.pas.common.vo.es.PatentFamilyMessageWithId;
  18. import cn.cslg.pas.domain.es.*;
  19. import cn.cslg.pas.exception.XiaoShiException;
  20. import cn.cslg.pas.service.business.CommonService;
  21. import cn.cslg.pas.service.common.PatentStarApiService;
  22. import cn.cslg.pas.service.importPatent.WebVOTransformService;
  23. import cn.cslg.pas.service.query.FormatQueryService;
  24. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  25. import co.elastic.clients.elasticsearch._types.*;
  26. import co.elastic.clients.elasticsearch._types.aggregations.*;
  27. import co.elastic.clients.elasticsearch._types.query_dsl.*;
  28. import co.elastic.clients.elasticsearch.core.*;
  29. import co.elastic.clients.elasticsearch.core.search.FieldCollapse;
  30. import co.elastic.clients.elasticsearch.core.search.Hit;
  31. import co.elastic.clients.json.JsonData;
  32. import com.alibaba.fastjson.JSON;
  33. import lombok.RequiredArgsConstructor;
  34. import org.apache.commons.lang3.ObjectUtils;
  35. import org.apache.commons.lang3.StringUtils;
  36. import org.springframework.beans.BeanUtils;
  37. import org.springframework.beans.factory.annotation.Autowired;
  38. import org.springframework.context.annotation.Lazy;
  39. import org.springframework.stereotype.Service;
  40. import org.springframework.transaction.annotation.Propagation;
  41. import org.springframework.transaction.annotation.Transactional;
  42. import org.springframework.util.CollectionUtils;
  43. import java.io.IOException;
  44. import java.text.SimpleDateFormat;
  45. import java.util.*;
  46. import java.util.stream.Collectors;
  47. import static org.springframework.data.elasticsearch.annotations.TermVector.no;
  48. @Service
  49. @RequiredArgsConstructor(onConstructor_ = {@Lazy})
  50. public class EsService {
  51. public final List<String> dateList = Arrays.asList("AD", "PD", "GD", "EXD", "PAD", "PED", "PPD", "EPD");
  52. private final ElasticsearchClient client;
  53. @Autowired
  54. private EsFamilyService esFamilyService;
  55. @Autowired
  56. private PatentStarApiService patentStarApiService;
  57. @Autowired
  58. private EsPatentService esPatentService;
  59. @Lazy
  60. @Autowired
  61. private EsCountService esCountService;
  62. @Autowired
  63. private EsCustomFieldService esCustomFieldService;
  64. /**
  65. * @param patent
  66. * @throws Exception
  67. */
  68. public String addPatent(Patent patent) throws Exception {
  69. IndexResponse indexResponse = client.index(i -> i
  70. .index("patent")
  71. //传入user对象
  72. .document(patent)
  73. );
  74. return indexResponse.id();
  75. }
  76. /**
  77. * @param patent
  78. * @throws Exception
  79. */
  80. public String addChildPatent(Patent patent, String id) throws Exception {
  81. IndexResponse indexResponse = client.index(i -> i
  82. .index("patent")
  83. .routing(id)
  84. //传入user对象
  85. .document(patent).refresh(Refresh.True).waitForActiveShards(WaitForActiveShards.of(t -> t.count(1)))
  86. );
  87. return indexResponse.id();
  88. }
  89. /**
  90. * 根据专利号获取专利id
  91. *
  92. * @param patentNo
  93. * @return
  94. * @throws Exception
  95. */
  96. public PatentWithIdVO getIdByPatentNo(String patentNo) throws Exception {
  97. SearchRequest.Builder builder = new SearchRequest.Builder();
  98. //设置查询索引
  99. builder.index("patent");
  100. PatentWithIdVO patentWithIdVO = null;
  101. String id = null;
  102. Query q1 = QueryBuilders.term(t -> t.field("app_no.keyword").value(patentNo));
  103. //公开号
  104. Query q2 = QueryBuilders.term(t -> t.field("public_no.keyword").value(patentNo));
  105. //授权号
  106. Query q3 = QueryBuilders.term(t -> t.field("grant_no.keyword").value(patentNo));
  107. Query query = QueryBuilders.bool(i -> i.should(q1, q2, q3));
  108. builder.query(query);
  109. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  110. List<Hit<Patent>> hits = response.hits().hits();
  111. if (hits != null && hits.size() > 0) {
  112. id = hits.get(0).id();
  113. Patent patent = hits.get(0).source();
  114. patentWithIdVO = new PatentWithIdVO();
  115. patentWithIdVO.setPatent(patent);
  116. patentWithIdVO.setId(id);
  117. }
  118. return patentWithIdVO;
  119. }
  120. /**
  121. * Es检索
  122. *
  123. * @param queryRequest 检索条件
  124. * @return
  125. */
  126. public PatentDTO esSearch(QueryRequest queryRequest) throws Exception {
  127. PatentDTO dto = new PatentDTO();
  128. Integer taskId = queryRequest.getTaskId();
  129. String searchCondition = "";
  130. Integer projectId = queryRequest.getProjectId();
  131. Integer productId = queryRequest.getProductId();
  132. String productFrom = queryRequest.getFrom();
  133. Long current = queryRequest.getCurrent();
  134. Long size = queryRequest.getSize();
  135. String groupField = queryRequest.getGroupField();
  136. //判断表达式
  137. if (queryRequest instanceof StringRequest) {
  138. searchCondition = ((StringRequest) queryRequest).getSearchQuery();
  139. } else if (queryRequest instanceof MapRequest) {
  140. Map<String, Object> map = ((MapRequest) queryRequest).getSearchQuery();
  141. StringBuilder stringBuilder = new StringBuilder();
  142. for (String key : map.keySet()) {
  143. Object value = map.get(key);
  144. if (!"".contentEquals(stringBuilder)) {
  145. stringBuilder = stringBuilder.append(" AND ").append(key).append("=").append(value);
  146. } else {
  147. stringBuilder = stringBuilder.append(key).append("=").append(value);
  148. }
  149. }
  150. searchCondition = stringBuilder.toString();
  151. }
  152. //判断同族分组
  153. String esField = "";
  154. if (StringUtils.isNotEmpty(groupField) && !groupField.equals("0")) {
  155. esField = this.getGroupField(groupField);
  156. }
  157. EsPatentCommonVO commonVO = new EsPatentCommonVO();
  158. commonVO.setTaskId(taskId);
  159. commonVO.setProjectId(projectId);
  160. commonVO.setProductId(productId);
  161. commonVO.setSearchCondition(searchCondition);
  162. commonVO.setProductFrom(productFrom);
  163. commonVO.setCurrent(current);
  164. commonVO.setSize(size);
  165. commonVO.setEsField(esField);
  166. commonVO.setCustomFields(queryRequest.getCustomFields());
  167. commonVO.setOrderDTOList(queryRequest.getOrderDTOList());
  168. SearchRequest.Builder builder = this.getCommonPatent(commonVO);
  169. //解除最大条数限制
  170. builder.trackTotalHits(i -> i.enabled(true));
  171. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  172. List<PatentColumnDTO> list = new ArrayList<>();
  173. List<Hit<Patent>> hits = response.hits().hits();
  174. long total = 0L;
  175. if (StringUtils.isNotEmpty(esField)) {
  176. Aggregate aggregate = response.aggregations().get("count");
  177. total = aggregate.cardinality().value();
  178. } else {
  179. total = response.hits().total().value();
  180. }
  181. for (Hit<Patent> hit : hits) {
  182. String id = hit.id();
  183. Patent esMess = hit.source();
  184. PatentColumnDTO columnDTO = this.getPatentColumnDTO(esMess, projectId, id);
  185. list.add(columnDTO);
  186. }
  187. this.loadCoulumnDTO(list);
  188. dto.setTotal(total);
  189. dto.setPatents(list);
  190. dto.setPageNum(current);
  191. dto.setPageSize(size);
  192. return dto;
  193. }
  194. //获取分组字段栏位
  195. public String getGroupField(String groupField) {
  196. String esField = "";
  197. switch (groupField) {
  198. case "simpleFamilyId":
  199. esField = "simple_family_id";
  200. break;
  201. case "inpadocFamilyId":
  202. esField = "inpadoc_family_id";
  203. break;
  204. case "patsnapFamilyId":
  205. esField = "patsnap_family_id";
  206. break;
  207. default:
  208. esField = "0";
  209. break;
  210. }
  211. return esField;
  212. }
  213. //获取通用检索专利方法--服务检索专利清单
  214. public SearchRequest.Builder getCommonPatent(EsPatentCommonVO commonVO) throws Exception {
  215. String esField = commonVO.getEsField();
  216. //计算分页信息
  217. Long current = commonVO.getCurrent();
  218. Long size = commonVO.getSize();
  219. Long startNum = commonVO.getStartNum();
  220. Long endNum = commonVO.getEndNum();
  221. Integer temPageFrom = 0;
  222. Integer temPageSize = 100000;
  223. if (current != null && size != null) {
  224. temPageFrom = (current.intValue() - 1) * size.intValue();
  225. temPageSize = size.intValue();
  226. } else if (startNum != null && endNum != null) {
  227. temPageFrom = startNum.intValue() - 1;
  228. temPageSize = (endNum.intValue() - startNum.intValue()) + 1;
  229. }
  230. Integer pageFrom = temPageFrom;
  231. Integer pageSize = temPageSize;
  232. SearchRequest.Builder builder = new SearchRequest.Builder();
  233. //设置查询索引
  234. builder.index("patent");
  235. Query reQuery = esPatentService.getEntireNotInQuery(commonVO);
  236. //判断同族分组
  237. if (StringUtils.isNotEmpty(esField)) {
  238. Query existQ = QueryBuilders.exists(i -> i.field(esField));
  239. Query bool = QueryBuilders.bool(i -> i.must(reQuery, existQ));
  240. builder.query(bool);
  241. FieldCollapse collapse = FieldCollapse.of(i -> i.field(esField));
  242. builder.collapse(collapse);
  243. //统计总数
  244. Aggregation aggregation = AggregationBuilders.cardinality(i -> i.field(esField));
  245. builder.aggregations("count", aggregation);
  246. } else {
  247. builder.query(reQuery);
  248. }
  249. builder.from(pageFrom).size(pageSize);
  250. //排序
  251. List<OrderDTO> dtoList = commonVO.getOrderDTOList();
  252. List<SortOptions> optionsList = this.getCommonSortMethod(dtoList);
  253. builder.sort(optionsList);
  254. return builder;
  255. }
  256. //获取通用检索专利方法--服务于批量删除、标引、查询价值曲线、导出excel、pdf首页
  257. public SearchRequest.Builder getCommonPatentByGroup(EsPatentCommonVO commonVO) throws Exception {
  258. String esField = commonVO.getEsField();
  259. Query reQuery = esPatentService.getEntireNotInQuery(commonVO);
  260. SearchRequest.Builder builder = new SearchRequest.Builder();
  261. //设置查询索引
  262. builder.index("patent");
  263. //判断同族分组
  264. if (StringUtils.isNotEmpty(esField)) {
  265. Query existQ = QueryBuilders.exists(i -> i.field(esField));
  266. Query bool = QueryBuilders.bool(i -> i.must(reQuery, existQ));
  267. builder.query(bool);
  268. FieldCollapse collapse = FieldCollapse.of(i -> i.field(esField));
  269. builder.collapse(collapse);
  270. } else {
  271. builder.query(reQuery);
  272. }
  273. //排序
  274. List<OrderDTO> dtoList = commonVO.getOrderDTOList();
  275. List<SortOptions> optionsList = this.getCommonSortMethod(dtoList);
  276. builder.sort(optionsList);
  277. return builder;
  278. }
  279. public PatentWithIdVO getPatentColumnDTOByGroup2(String key, Integer projectId, String field) throws Exception {
  280. PatentWithIdVO dto = new PatentWithIdVO();
  281. SearchRequest.Builder builder = new SearchRequest.Builder();
  282. //设置查询索引
  283. builder.index("patent");
  284. Query query = QueryBuilders.term(i -> i.field("project_id").value(projectId));
  285. Query q1 = QueryBuilders.hasChild(i -> i.type("project").query(query));
  286. Query q2 = QueryBuilders.term(i -> i.field(field).value(key));
  287. Query bool = QueryBuilders.bool(i -> i.must(q1, q2));
  288. builder.query(bool);
  289. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  290. List<Hit<Patent>> hits = response.hits().hits();
  291. if (!CollectionUtils.isEmpty(hits)) {
  292. String id = hits.get(0).id();
  293. Patent patent = hits.get(0).source();
  294. dto.setPatent(patent);
  295. dto.setId(id);
  296. }
  297. return dto;
  298. }
  299. /**
  300. * 获取公共排序方法
  301. *
  302. * @param dtoList
  303. * @return
  304. */
  305. public List<SortOptions> getCommonSortMethod(List<OrderDTO> dtoList) {
  306. List<SortOptions> optionsList = new ArrayList<>();
  307. if (!CollectionUtils.isEmpty(dtoList)) {
  308. String json = CommonService.readJsonFile("patent.json");
  309. List<EsConfigVO> esConfigVOS = JSON.parseArray(json, EsConfigVO.class);
  310. for (OrderDTO orderDTO : dtoList) {
  311. EsConfigVO configVO = esConfigVOS.stream().filter(item -> item.getField().equals(orderDTO.getOrderBy())).findFirst().orElse(null);
  312. if (configVO != null) {
  313. if (orderDTO.getOrderType().equals(IfConstant.NO)) {
  314. SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field(configVO.getEsField()).order(SortOrder.Asc).missing(-1)));
  315. optionsList.add(sortOptions);
  316. } else {
  317. SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field(configVO.getEsField()).order(SortOrder.Desc).missing(-1)));
  318. optionsList.add(sortOptions);
  319. }
  320. }
  321. }
  322. } else {
  323. SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field("patent_no.keyword").order(SortOrder.Desc).missing(-1)));
  324. optionsList.add(sortOptions);
  325. }
  326. return optionsList;
  327. }
  328. //装载专利清单列表的数据
  329. public PatentColumnDTO getPatentColumnDTO(Patent patent, Integer projectId, String id) {
  330. PatentColumnDTO columnDTO = new PatentColumnDTO();
  331. BeanUtils.copyProperties(patent, columnDTO);
  332. if (!CollectionUtils.isEmpty(patent.getIpc())) {
  333. boolean b = patent.getIpc().stream().allMatch(Objects::isNull);
  334. if (b) {
  335. columnDTO.setIpc(new ArrayList<>());
  336. }
  337. }
  338. if (projectId != null) {
  339. try {
  340. columnDTO.setMergeApplicant(esPatentService.getMergeApp(projectId, id));
  341. } catch (IOException e) {
  342. columnDTO.setMergeApplicant(new ArrayList<>());
  343. }
  344. try {
  345. columnDTO.setMergeRightHolder(esPatentService.getMergeRight(projectId, id));
  346. } catch (IOException e) {
  347. columnDTO.setMergeRightHolder(new ArrayList<>());
  348. }
  349. try {
  350. columnDTO.setMergeInventor(esPatentService.getMergeInventor(projectId, id));
  351. } catch (IOException e) {
  352. columnDTO.setMergeInventor(new ArrayList<>());
  353. }
  354. }
  355. if (ObjectUtils.isNotEmpty(patent.getApplicantAddr())) {
  356. PersonAddress applicantAddr = patent.getApplicantAddr();
  357. columnDTO.setAppAddress(applicantAddr.getAddress());
  358. columnDTO.setApplicantCountry(applicantAddr.getCountry());
  359. columnDTO.setAppProvince(applicantAddr.getProvince());
  360. columnDTO.setAppCity(applicantAddr.getCity());
  361. columnDTO.setAppDistrict(applicantAddr.getDistrict());
  362. }
  363. if (ObjectUtils.isNotEmpty(patent.getRightHolderAddr())) {
  364. PersonAddress rightAddr = patent.getRightHolderAddr();
  365. columnDTO.setRightAddress(rightAddr.getAddress());
  366. columnDTO.setRightCountry(rightAddr.getCountry());
  367. columnDTO.setRightProvince(rightAddr.getProvince());
  368. columnDTO.setRightCity(rightAddr.getCity());
  369. columnDTO.setRightDistrict(rightAddr.getDistrict());
  370. }
  371. if (!CollectionUtils.isEmpty(patent.getPriorities())) {
  372. List<Priorities> priorities = patent.getPriorities();
  373. List<String> priorityCountrys = priorities.stream().map(Priorities::getPriorityCountry).distinct().collect(Collectors.toList());
  374. String priorityCountry = String.join("<br>", priorityCountrys);
  375. columnDTO.setPriorityCountry(priorityCountry);
  376. List<String> priorityNos = priorities.stream().map(Priorities::getPriorityNo).distinct().collect(Collectors.toList());
  377. String priorityNo = String.join("<br>", priorityNos);
  378. columnDTO.setPriorityNo(priorityNo);
  379. List<String> priorityDates = priorities.stream().map(Priorities::getPriorityDate).distinct().collect(Collectors.toList());
  380. String priorityDate = String.join("<br>", priorityDates);
  381. if (priorityDate.contains("null")) {
  382. columnDTO.setPriorityDate("");
  383. } else {
  384. columnDTO.setPriorityDate(priorityDate);
  385. }
  386. }
  387. columnDTO.setApplicant(esPatentService.loadName(patent.getApplicant()));
  388. columnDTO.setRightHolder(esPatentService.loadName(patent.getRightHolder()));
  389. columnDTO.setInventor(esPatentService.loadName(patent.getInventor()));
  390. return columnDTO;
  391. }
  392. //拼接专题库id或其他id条件
  393. public String appendIdsCondition(String searchCondition, Integer taskId, String productFrom, Integer projectId, Integer productId) {
  394. String condition = "";
  395. if (taskId != null) {
  396. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  397. searchCondition = "taskId = " + taskId + " AND " + searchCondition;
  398. } else {
  399. searchCondition = "taskId = " + taskId;
  400. }
  401. } else {
  402. if (StringUtils.isNotEmpty(productFrom)) {
  403. if (productId != null) {
  404. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  405. searchCondition = "productId = " + productId + " AND " + searchCondition;
  406. } else {
  407. searchCondition = "productId = " + productId;
  408. }
  409. }
  410. } else {
  411. if (projectId != null) {
  412. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  413. searchCondition = "projectId = " + projectId + " AND " + searchCondition;
  414. } else {
  415. searchCondition = "projectId = " + projectId;
  416. }
  417. }
  418. }
  419. }
  420. condition = searchCondition;
  421. return condition;
  422. }
  423. /**
  424. * 解析自定义栏位和值
  425. *
  426. * @param customFields
  427. * @return
  428. */
  429. public String parseCustomField(List<EsCustomFieldValueDTO> customFields, Integer projectId, Integer taskId) throws Exception {
  430. int m = 1;
  431. int n = 0;
  432. StringBuilder builder = new StringBuilder();
  433. long start = System.currentTimeMillis();
  434. if (customFields.size() > m) {
  435. for (int i = 0; i < customFields.size(); i++) {
  436. EsCustomFieldValueDTO customField = customFields.get(i);
  437. if (i != n) {
  438. builder.append(" ").append("and").append(" ").append("(");
  439. this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
  440. } else {
  441. builder.append("(");
  442. this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
  443. }
  444. }
  445. } else {
  446. for (int i = 0; i < customFields.size(); i++) {
  447. EsCustomFieldValueDTO customField = customFields.get(i);
  448. if (i != n) {
  449. builder.append(" ").append("and").append(" ");
  450. this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
  451. } else {
  452. builder.append("(");
  453. this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
  454. }
  455. }
  456. }
  457. long end = System.currentTimeMillis();
  458. System.out.println("耗时" + (end - start));
  459. return builder.toString();
  460. }
  461. //拼接自定义栏位
  462. public void appendStr(EsCustomFieldValueDTO customField, StringBuilder builder, int m, boolean ifHaveChild,
  463. Integer projectId, Integer taskId) throws Exception {
  464. builder.append("field").append("=").append(customField.getFieldId());
  465. List<String> values = customField.getFieldValue();
  466. if (values.contains("未选择")) {
  467. values.removeIf(value -> value.equals("未选择"));
  468. values.add("未选择");
  469. }
  470. if (!CollectionUtils.isEmpty(values)) {
  471. builder.append(" ").append("and").append(" ");
  472. if (ifHaveChild) {
  473. builder.append("statsValue").append("=");
  474. } else {
  475. builder.append("fieldValue").append("=");
  476. }
  477. if (values.size() > m) {
  478. builder.append("(");
  479. for (int j = 0; j < values.size(); j++) {
  480. String s = values.get(j);
  481. if (j != values.size() - m) {
  482. builder.append(s).append(" ").append("or").append(" ");
  483. } else {
  484. if (s.equals("未选择")) {
  485. GetUnselectedDTO unselectedDTO = esCountService.getUnselectedCustomNum(projectId, customField.getFieldId());
  486. List<String> childIds = unselectedDTO.getBeinglessChildIds();
  487. String noCondition = this.appendIds(childIds);
  488. builder.append(s).append(")").append(" ").append("OR")
  489. .append(" ").append("(").append(noCondition).append(")").append(")");
  490. } else {
  491. builder.append(s).append(")").append(")");
  492. }
  493. }
  494. }
  495. } else {
  496. for (String value : values) {
  497. if (value.equals("未选择")) {
  498. GetUnselectedDTO unselectedDTO = esCountService.getUnselectedCustomNum(projectId, customField.getFieldId());
  499. List<String> childIds = unselectedDTO.getBeinglessChildIds();
  500. String noCondition = this.appendIds(childIds);
  501. builder.append(value).append(" ").append("OR").append(" ").append(noCondition).append(")");
  502. } else {
  503. builder.append(value).append(")");
  504. }
  505. }
  506. }
  507. } else {
  508. builder.append(")");
  509. }
  510. }
  511. //拼接专利ids
  512. public String appendIds(List<String> nos) {
  513. String str = "ids = ";
  514. if (nos.size() > 1) {
  515. str = str + "\"";
  516. for (int i = 0; i < nos.size(); i++) {
  517. String s = nos.get(i);
  518. if (i != nos.size() - 1) {
  519. str = str + s + ",";
  520. } else {
  521. str = str + s + "\"";
  522. }
  523. }
  524. } else {
  525. for (String no : nos) {
  526. str = str + no;
  527. }
  528. }
  529. return str;
  530. }
  531. //拼接专利号NOS
  532. public String appendNOS(List<String> nos) {
  533. String str = "NO = ";
  534. if (nos.size() > 1) {
  535. str = str + "(";
  536. for (int i = 0; i < nos.size(); i++) {
  537. String s = nos.get(i);
  538. if (i != nos.size() - 1) {
  539. str = str + s + " " + "OR" + " ";
  540. } else {
  541. str = str + s + ")";
  542. }
  543. }
  544. } else {
  545. for (String no : nos) {
  546. str = str + no;
  547. }
  548. }
  549. return str;
  550. }
  551. //更新patent
  552. public Integer updatePatent(Patent patent, String id) {
  553. UpdateRequest<Patent, Patent> req;
  554. req = UpdateRequest.of(
  555. b -> b.index("patent").id(id)
  556. .doc(patent)
  557. );
  558. try {
  559. client.update(req, Patent.class);
  560. return 1;
  561. } catch (IOException e) {
  562. return -1;
  563. }
  564. }
  565. //更新patent
  566. public Integer updatePatentShouldWait(Patent patent, String id) {
  567. UpdateRequest<Patent, Patent> req;
  568. req = UpdateRequest.of(
  569. b -> b.index("patent").id(id)
  570. .doc(patent).refresh(Refresh.True)
  571. );
  572. try {
  573. client.update(req, Patent.class);
  574. return 1;
  575. } catch (IOException e) {
  576. return -1;
  577. }
  578. }
  579. //更新patent
  580. public Integer updatePatentById(Patent patent, String id) {
  581. UpdateRequest<Patent, Patent> req;
  582. req = UpdateRequest.of(
  583. b -> b.index("patent").id(id)
  584. .doc(patent));
  585. try {
  586. client.update(req, Patent.class);
  587. return 1;
  588. } catch (IOException e) {
  589. return -1;
  590. }
  591. }
  592. //获取父文档相关的所有自定义子文档,按照时间按倒序,首个改为最新数据,其他if——new改为0:不是最新
  593. public Integer getIds(String parentId, Integer projectId, Integer taskId, String fieldId) throws Exception {
  594. int ifNew = 0;
  595. SearchRequest.Builder builder = new SearchRequest.Builder();
  596. //设置查询索引
  597. builder.index("patent");
  598. Query q1 = QueryBuilders.hasParent(i -> i.parentType("patent").query(j -> j.ids(IdsQuery.of(k -> k.values(parentId)))));
  599. Query q2 = QueryBuilders.exists(i -> i.field("custom_field"));
  600. Query q3 = QueryBuilders.term(i -> i.field("custom_field.project_id").value(projectId));
  601. Query q4 = QueryBuilders.term(i -> i.field("custom_field.field").value(fieldId));
  602. Query bool = QueryBuilders.bool(i -> i.must(q1, q2, q3, q4));
  603. builder.query(bool);
  604. List<SortOptions> optionsList = new ArrayList<>();
  605. SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field("custom_field.create_time").order(SortOrder.Desc).missing(-1)));
  606. optionsList.add(sortOptions);
  607. builder.sort(optionsList);
  608. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  609. List<Hit<Patent>> hits = response.hits().hits();
  610. Map<String, ESCustomField> map = new HashMap<>();
  611. for (Hit<Patent> hit : hits) {
  612. String id = hit.id();
  613. Patent patent = hit.source();
  614. map.put(id, patent.getESCustomField());
  615. }
  616. if (!CollectionUtils.isEmpty(map)) {
  617. for (String id : map.keySet()) {
  618. ESCustomField esCustomField = map.get(id);
  619. esCustomField.setIfNew(0);
  620. Patent patent = new Patent();
  621. patent.setESCustomField(esCustomField);
  622. Integer aNew = this.updateCustomFieldIfNew(patent, id);
  623. if (aNew > 0) {
  624. ifNew++;
  625. } else {
  626. ifNew = 0;
  627. break;
  628. }
  629. }
  630. }
  631. return ifNew;
  632. }
  633. //更新自定义文档是否是最新数据
  634. public Integer updateCustomFieldIfNew(Patent patent, String id) throws IOException {
  635. ESCustomField customField = patent.getESCustomField();
  636. String source = "ctx._source.custom_field.if_new = " + customField.getIfNew();
  637. InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").source(source));
  638. Script script = Script.of(i -> i.inline(inlineScript));
  639. Query query = QueryBuilders.term(i -> i.field("_id").value(id));
  640. UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).refresh(true).query(query));
  641. try {
  642. client.updateByQuery(request);
  643. return 1;
  644. } catch (IOException e) {
  645. return -1;
  646. }
  647. }
  648. //更新子文档
  649. public Integer updateByQuery(Patent patent, String id) throws Exception {
  650. ESCustomField customField = patent.getESCustomField();
  651. String parentId = patent.getPatentJoin().getParent();
  652. Integer num = this.getIds(parentId, customField.getProjectId(), customField.getTaskId(), customField.getField());
  653. if (num < 1) {
  654. throw new XiaoShiException("子文档是否最新更新失败");
  655. }
  656. String valueField = "[";
  657. List<String> fieldValueList = customField.getFieldValue();
  658. if (!CollectionUtils.isEmpty(fieldValueList)) {
  659. int lastSum = fieldValueList.size() - 1;
  660. for (int i = 0; i < fieldValueList.size(); i++) {
  661. String s = fieldValueList.get(i);
  662. if (i == lastSum) {
  663. valueField = valueField + "\"" + s + "\"";
  664. } else {
  665. valueField = valueField + "\"" + s + "\"" + ",";
  666. }
  667. }
  668. }
  669. valueField = valueField + "]";
  670. String valueStats = "[";
  671. List<String> statsValueList = customField.getStatsValue();
  672. if (!CollectionUtils.isEmpty(statsValueList)) {
  673. int lastSum = statsValueList.size() - 1;
  674. for (int i = 0; i < statsValueList.size(); i++) {
  675. String s = statsValueList.get(i);
  676. if (i == lastSum) {
  677. valueStats = valueStats + "\"" + s + "\"";
  678. } else {
  679. valueStats = valueStats + "\"" + s + "\"" + ",";
  680. }
  681. }
  682. }
  683. valueStats = valueStats + "]";
  684. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  685. String s = format.format(customField.getCreateTime());
  686. String dateStr = "\'" + s + "\'";
  687. String projectId = "ctx._source.custom_field.project_id = " + customField.getProjectId() + ";";
  688. String taskId = "ctx._source.custom_field.task_id = " + customField.getTaskId() + ";";
  689. String ifNew = "ctx._source.custom_field.if_new = " + 1 + ";";
  690. String field = "ctx._source.custom_field.field=" + customField.getField() + ";";
  691. String fieldType = "ctx._source.custom_field.field_type = " + customField.getFieldType() + ";";
  692. String personId = "ctx._source.custom_field.person_id = " + customField.getPersonId() + ";";
  693. String createTime = "ctx._source.custom_field.create_time = " + dateStr + ";";
  694. String fieldValue = "ctx._source.custom_field.field_value = " + valueField + ";";
  695. String statsValue = "ctx._source.custom_field.stats_value = " + valueStats;
  696. String source = projectId + taskId + ifNew + field + fieldType + personId + createTime + fieldValue + statsValue;
  697. InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").source(source));
  698. Script script = Script.of(i -> i.inline(inlineScript));
  699. Query query = QueryBuilders.term(i -> i.field("_id").value(id));
  700. UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).refresh(true).query(query));
  701. try {
  702. client.updateByQuery(request);
  703. return 1;
  704. } catch (IOException e) {
  705. return -1;
  706. }
  707. }
  708. /**
  709. * @param key
  710. * @param page
  711. * @param limit
  712. * @return
  713. * @throws IOException
  714. */
  715. public List<Patent> searchChild(String key, Integer page, Integer limit) throws IOException {
  716. SearchRequest.Builder builder = new SearchRequest.Builder();
  717. //设置查询索引
  718. builder.index("patent");
  719. //组装查询条件
  720. HasChildQuery.Builder hasChildQuery = new HasChildQuery.Builder();
  721. hasChildQuery.type("project");
  722. hasChildQuery.query(q -> q.match(m -> m
  723. .query(key)
  724. //字段名
  725. .field("project_id")
  726. ));
  727. builder.query(q -> q.hasChild(hasChildQuery.build()));
  728. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  729. List<Patent> list = new ArrayList<>();
  730. List<Hit<Patent>> hits = response.hits().hits();
  731. for (Hit<Patent> hit : hits) {
  732. Patent esMess = hit.source();
  733. list.add(esMess);
  734. }
  735. return list;
  736. }
  737. /**
  738. * 查询是否存在专利
  739. *
  740. * @param parentId
  741. * @param projectId
  742. * @return
  743. */
  744. public Boolean searchPatent(String parentId, Integer projectId) throws IOException {
  745. boolean flag = false;
  746. SearchRequest.Builder builder = new SearchRequest.Builder();
  747. //设置查询索引
  748. builder.index("patent");
  749. Query q1 = QueryBuilders.term(t -> t.field("project_id").value(projectId));
  750. Query q2 = QueryBuilders.parentId(parent -> parent.type("project").id(parentId));
  751. Query bool = QueryBuilders.bool(i -> i.must(q1, q2));
  752. builder.query(bool);
  753. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  754. long total = response.hits().total().value();
  755. if (total > 0) {
  756. flag = true;
  757. }
  758. return flag;
  759. }
  760. /**
  761. * 查询是否存在专利
  762. *
  763. * @param parentId
  764. * @param projectId
  765. * @return
  766. */
  767. public Boolean ifInTask(String parentId, Integer projectId, Integer taskId) throws IOException {
  768. boolean flag = false;
  769. SearchRequest.Builder builder = new SearchRequest.Builder();
  770. //设置查询索引
  771. builder.index("patent");
  772. Query q1 = QueryBuilders.term(t -> t.field("import_task.project_id").value(projectId));
  773. Query q3 = QueryBuilders.term(t -> t.field("import_task.task_id").value(projectId));
  774. Query q2 = QueryBuilders.parentId(parent -> parent.type("import_task").id(parentId));
  775. Query bool = QueryBuilders.bool(i -> i.must(q1, q2, q3));
  776. builder.query(bool);
  777. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  778. long total = response.hits().total().value();
  779. if (total > 0) {
  780. flag = true;
  781. }
  782. return flag;
  783. }
  784. /**
  785. * 查询同族
  786. *
  787. * @param nos
  788. * @param type
  789. * @return
  790. * @throws IOException
  791. */
  792. public EsPatentFamilyDTO addEsPatentFamily(Patent patent, List<String> nos, String type) throws Exception {
  793. EsPatentFamilyDTO esDTO = new EsPatentFamilyDTO();
  794. List<String> newNos = new ArrayList<>();
  795. nos.forEach(item -> newNos.add(item.trim()));
  796. nos = newNos;
  797. PatentFamilyMessage patentFamilyMessage = null;
  798. List<FamilyPatent> familyPatents = new ArrayList<>();
  799. String id = "";
  800. PatentFamilyMessageWithId patentFamilyMessageWithId = queryPatentFamily(patent, type);
  801. if (patentFamilyMessageWithId != null) {
  802. patentFamilyMessage = patentFamilyMessageWithId.getPatentFamilyMessage();
  803. id = patentFamilyMessageWithId.getId();
  804. } else {
  805. //遍历,根据专利号查询同族
  806. for (String no : nos) {
  807. SearchRequest.Builder builder = new SearchRequest.Builder();
  808. //设置查询索引
  809. builder.index("patent_family");
  810. //申请号
  811. Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(no));
  812. //公开号
  813. Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(no));
  814. //授权号
  815. Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(no));
  816. //类型
  817. Query q4 = QueryBuilders.term(t -> t.field("family_type").value(type));
  818. Query p = QueryBuilders.bool(i -> i.should(q1, q2, q3));
  819. Query bool = QueryBuilders.bool(i -> i.must(q4, p));
  820. builder.query(bool);
  821. SearchResponse<PatentFamilyMessage> response = client.search(builder.build(), PatentFamilyMessage.class);
  822. long total = response.hits().total().value();
  823. if (total > 0) {
  824. List<FamilyPatent> list = new ArrayList<>();
  825. List<Hit<PatentFamilyMessage>> hits = response.hits().hits();
  826. Hit<PatentFamilyMessage> hit = hits.get(0);
  827. id = hit.id();
  828. patentFamilyMessage = hit.source();
  829. break;
  830. }
  831. }
  832. }
  833. if (patentFamilyMessage == null) {
  834. patentFamilyMessage = new PatentFamilyMessage();
  835. patentFamilyMessage.setFamilyType(type);
  836. } else {
  837. familyPatents = patentFamilyMessage.getPatent();
  838. familyPatents = this.getDistFamilyPatents(familyPatents);
  839. }
  840. //装载专利
  841. String appNo = "";
  842. String publicNo = "";
  843. String grantNo = "";
  844. if (patent.getAppNo() != null) {
  845. appNo = patent.getAppNo();
  846. }
  847. if (patent.getPublicNo() != null) {
  848. publicNo = patent.getPublicNo();
  849. }
  850. if (patent.getGrantNo() != null) {
  851. grantNo = patent.getGrantNo();
  852. }
  853. String appNo1 = appNo;
  854. String publicNo1 = publicNo;
  855. String grantNo1 = grantNo;
  856. FamilyPatent patent1 = familyPatents.stream().filter(item ->
  857. publicNo1.equals(item.getPublicNo()) || publicNo1.equals(item.getGrantNo()) || publicNo1.equals(item.getAppNo()) || grantNo1.equals(item.getPublicNo())
  858. || grantNo1.equals(item.getGrantNo()) || grantNo1.equals(item.getAppNo()) || appNo1.equals(item.getAppNo()) || appNo1.equals(item.getPublicNo()) || appNo1.equals(item.getGrantNo())
  859. ).findFirst().orElse(null);
  860. if (patent1 == null) {
  861. patent1 = new FamilyPatent();
  862. patent1.setGrantNo(patent.getGrantNo());
  863. patent1.setAppNo(patent.getAppNo());
  864. patent1.setPublicNo(patent.getPublicNo());
  865. familyPatents.add(patent1);
  866. } else {
  867. patent1.setGrantNo(patent.getGrantNo());
  868. patent1.setAppNo(patent.getAppNo());
  869. patent1.setPublicNo(patent.getPublicNo());
  870. }
  871. //装载专利号
  872. familyPatents = this.getDistFamilyPatentsWithNos(familyPatents, nos);
  873. patentFamilyMessage.setPatent(familyPatents);
  874. //当id不为null时
  875. if (!id.equals("")) {
  876. this.updatePatentFamily(patentFamilyMessage, id);
  877. } else {
  878. try {
  879. id = this.addPatentFamily(patentFamilyMessage);
  880. } catch (Exception e) {
  881. }
  882. }
  883. if (familyPatents != null && familyPatents.size() > 0) {
  884. List<String> temNos = new ArrayList<>();
  885. familyPatents.forEach(item -> {
  886. if (item.getGrantNo() != null) {
  887. temNos.add(item.getGrantNo());
  888. } else if (item.getPublicNo() != null) {
  889. temNos.add(item.getPublicNo());
  890. } else if (item.getAppNo() != null) {
  891. temNos.add(item.getAppNo());
  892. }
  893. });
  894. esFamilyService.updatePatentFamilyByQuery(type, id, familyPatents.size(), temNos);
  895. }
  896. esDTO.setPatentFamilyId(id);
  897. esDTO.setFamilyNum(patentFamilyMessage.getPatent().size());
  898. return esDTO;
  899. }
  900. private List<FamilyPatent> getDistFamilyPatents(List<FamilyPatent> familyPatents) {
  901. List<FamilyPatent> familyPatentsNew = new ArrayList<>();
  902. if (familyPatents == null || familyPatents.size() == 0) {
  903. return familyPatentsNew;
  904. }
  905. for (int i = 0; i < familyPatents.size(); i++) {
  906. FamilyPatent familyPatent = familyPatents.get(i);
  907. FamilyPatent familyPatentNew = familyPatentsNew.stream().filter(item -> (item.getPublicNo() != null && (item.getPublicNo().equals(familyPatent.getPublicNo()) || item.getPublicNo().equals(familyPatent.getAppNo()) || item.getPublicNo().equals(familyPatent.getGrantNo())))
  908. || (item.getGrantNo() != null && (item.getGrantNo().equals(familyPatent.getGrantNo()) || item.getGrantNo().equals(familyPatent.getPublicNo()) || item.getGrantNo().equals(familyPatent.getAppNo())) || (item.getAppNo() != null && (item.getAppNo().equals(familyPatent.getGrantNo()) || item.getAppNo().equals(familyPatent.getPublicNo()) || item.getAppNo().equals(familyPatent.getAppNo()))))).findFirst().orElse(null);
  909. if (familyPatentNew == null) {
  910. familyPatentsNew.add(familyPatent);
  911. } else {
  912. if (familyPatentNew.getAppNo() == null && familyPatent.getGrantNo() == null) {
  913. familyPatentsNew.remove(familyPatentNew);
  914. familyPatentsNew.add(familyPatent);
  915. }
  916. }
  917. }
  918. return familyPatentsNew;
  919. }
  920. private List<FamilyPatent> getDistFamilyPatentsWithNos(List<FamilyPatent> familyPatents, List<String> nos) {
  921. List<FamilyPatent> familyPatentsNew = new ArrayList<>();
  922. if (nos.size() == 0 || nos == null) {
  923. return familyPatents;
  924. }
  925. if (familyPatents == null) {
  926. familyPatents = new ArrayList<>();
  927. }
  928. for (int i = 0; i < nos.size(); i++) {
  929. FamilyPatent familyPatentNew = familyPatents.stream().filter(item -> (item.getPublicNo() != null && item.getPublicNo().equals(no))
  930. || (item.getGrantNo() != null && item.getGrantNo().equals(no) || (item.getAppNo() != null && item.getAppNo().equals(no)))).findFirst().orElse(null);
  931. if (familyPatentNew == null) {
  932. familyPatentNew = new FamilyPatent();
  933. familyPatentNew.setPublicNo(nos.get(i));
  934. familyPatents.add(familyPatentNew);
  935. }
  936. }
  937. return familyPatents;
  938. }
  939. /**
  940. * 添加同族
  941. *
  942. * @param message
  943. * @return
  944. * @throws Exception
  945. */
  946. public String addPatentFamily(PatentFamilyMessage message) throws Exception {
  947. IndexResponse indexResponse = client.index(i -> i
  948. .index("patent_family")
  949. .document(message)
  950. );
  951. return indexResponse.id();
  952. }
  953. /**
  954. * 更新同族
  955. *
  956. * @param message
  957. * @param id
  958. * @return
  959. */
  960. public Integer updatePatentFamily(PatentFamilyMessage message, String id) {
  961. UpdateRequest<PatentFamilyMessage, PatentFamilyMessage> req;
  962. req = UpdateRequest.of(
  963. b -> b.index("patent_family")
  964. .id(id)
  965. .doc(message)
  966. );
  967. try {
  968. client.update(req, PatentFamilyMessage.class);
  969. return 1;
  970. } catch (IOException e) {
  971. return -1;
  972. }
  973. }
  974. /**
  975. * 更新专利事务
  976. *
  977. * @param
  978. * @param id
  979. * @return
  980. */
  981. public Integer updateLegalEvent(LegalEvent legalEvent, String id) {
  982. UpdateRequest<LegalEvent, LegalEvent> req;
  983. req = UpdateRequest.of(
  984. b -> b.index("legal_event")
  985. .id(id)
  986. .doc(legalEvent).refresh(Refresh.True).waitForActiveShards(WaitForActiveShards.of(i -> i.count(1)))
  987. );
  988. try {
  989. client.update(req, LegalEvent.class);
  990. return 1;
  991. } catch (IOException e) {
  992. return -1;
  993. }
  994. }
  995. /**
  996. * 更新专利事务
  997. *
  998. * @param
  999. * @param id
  1000. * @return
  1001. */
  1002. public Integer updateQuotePatent(PatentQuoteMessage patentQuoteMessage, String id) {
  1003. UpdateRequest<PatentQuoteMessage, PatentQuoteMessage> req;
  1004. req = UpdateRequest.of(
  1005. b -> b.index("quote_patent")
  1006. .id(id)
  1007. .doc(patentQuoteMessage)
  1008. );
  1009. try {
  1010. client.update(req, PatentQuoteMessage.class);
  1011. return 1;
  1012. } catch (IOException e) {
  1013. return -1;
  1014. }
  1015. }
  1016. /**
  1017. * 添加法律事务
  1018. *
  1019. * @param
  1020. * @return
  1021. * @throws Exception
  1022. */
  1023. public String addQuotePatent(PatentQuoteMessage patentQuoteMessage) throws Exception {
  1024. IndexResponse indexResponse = client.index(i -> i
  1025. .index("quote_patent")
  1026. .document(patentQuoteMessage)
  1027. );
  1028. return indexResponse.id();
  1029. }
  1030. public PatentQuoteMessage addEsQuotePatent(Patent patent, List<String> nos) throws Exception {
  1031. if (patent == null) {
  1032. return null;
  1033. }
  1034. QuotePatent quotePatent = this.reQuotePatent(patent);
  1035. PatentQuoteMessage patentQuoteMessage = null;
  1036. //根据申请号和
  1037. String id = "";
  1038. //根据专利号查询是否有引用信息
  1039. SearchRequest.Builder builder = new SearchRequest.Builder();
  1040. //设置查询索引
  1041. builder.index("quote_patent");
  1042. //申请号
  1043. Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getAppNo()));
  1044. Query bool = QueryBuilders.bool(i -> i.must(q1));
  1045. builder.query(bool);
  1046. SearchResponse<PatentQuoteMessage> response = client.search(builder.build(), PatentQuoteMessage.class);
  1047. long total = response.hits().total().value();
  1048. if (total > 0) {
  1049. patentQuoteMessage = response.hits().hits().get(0).source();
  1050. id = response.hits().hits().get(0).id();
  1051. }
  1052. List<QuotePatent> quotePatents = new ArrayList<>();
  1053. if (patentQuoteMessage != null && patentQuoteMessage.getQuotedPatents() != null) {
  1054. quotePatents = patentQuoteMessage.getQuotedPatents();
  1055. }
  1056. if (nos != null && nos.size() > 0) {
  1057. List<Patent> patents = esPatentService.getPatentsByNo(nos, true, null, null);
  1058. for (String patentNo : nos) {
  1059. QuotePatent quotePatent1 = null;
  1060. if (quotePatents.size() > 0) {
  1061. quotePatent1 = quotePatents.stream()
  1062. .filter(item -> patentNo.equals(item.getAppNo()) || patentNo.equals(item.getPublicNo()) || patentNo.equals(item.getGrantNo())).findFirst().orElse(null);
  1063. }
  1064. Patent patent1 = patents.stream().filter(item -> patentNo.equals(item.getAppNo())).findFirst().orElse(null);
  1065. quotePatent1 = this.reQuotePatent(patent1, patentNo);
  1066. quotePatents.add(quotePatent1);
  1067. }
  1068. }
  1069. if (patentQuoteMessage == null) {
  1070. if (quotePatents.size() != 0) {
  1071. patentQuoteMessage = new PatentQuoteMessage();
  1072. patentQuoteMessage.setPatent(quotePatent);
  1073. patentQuoteMessage.setQuotedPatents(quotePatents);
  1074. this.addQuotePatent(patentQuoteMessage);
  1075. }
  1076. } else {
  1077. patentQuoteMessage.getQuotedPatents().addAll(quotePatents);
  1078. this.updateQuotePatent(patentQuoteMessage, id);
  1079. }
  1080. return patentQuoteMessage;
  1081. }
  1082. private QuotePatent reQuotePatent(Patent patent) {
  1083. QuotePatent quotePatent = new QuotePatent();
  1084. //装载申请人
  1085. quotePatent.setApplicant(patent.getApplicant());
  1086. //装载权利人
  1087. quotePatent.setRightHolder(patent.getRightHolder());
  1088. quotePatent.setAppNo(patent.getAppNo());
  1089. quotePatent.setGrantNo(patent.getGrantNo());
  1090. quotePatent.setPublicNo(patent.getPublicNo());
  1091. return quotePatent;
  1092. }
  1093. private QuotePatent reQuotePatent(Patent patent, String no) {
  1094. QuotePatent quotePatent = new QuotePatent();
  1095. if (patent == null) {
  1096. quotePatent.setPublicNo(no);
  1097. return quotePatent;
  1098. }
  1099. //装载申请人
  1100. quotePatent.setApplicant(patent.getApplicant());
  1101. quotePatent.setRightHolder(patent.getRightHolder());
  1102. quotePatent.setAppNo(patent.getAppNo());
  1103. quotePatent.setGrantNo(patent.getGrantNo());
  1104. quotePatent.setPublicNo(patent.getPublicNo());
  1105. return quotePatent;
  1106. }
  1107. /**
  1108. * 查询权利要求
  1109. *
  1110. * @param patentNo
  1111. * @return
  1112. */
  1113. public SelectClaimDTO selectClaim(String patentNo) throws IOException {
  1114. SearchRequest.Builder builder = new SearchRequest.Builder();
  1115. //设置查询索引
  1116. builder.index("patent");
  1117. //原始数据
  1118. Query q = QueryBuilders.term(t -> t.field("claim.if_origin").value(true));
  1119. //申请号
  1120. Query q1 = QueryBuilders.term(t -> t.field("app_no.keyword").value(patentNo));
  1121. //公开号
  1122. Query q2 = QueryBuilders.term(t -> t.field("public_no.keyword").value(patentNo));
  1123. //授权号
  1124. Query q3 = QueryBuilders.term(t -> t.field("grant_no.keyword").value(patentNo));
  1125. Query query = QueryBuilders.bool(i -> i.should(q1, q2, q3));
  1126. Query bool = QueryBuilders.bool(i -> i.must(q, query));
  1127. builder.query(bool);
  1128. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  1129. SelectClaimDTO dto = new SelectClaimDTO();
  1130. List<Hit<Patent>> hits = response.hits().hits();
  1131. for (Hit<Patent> hit : hits) {
  1132. Patent esMess = hit.source();
  1133. if (esMess != null) {
  1134. dto.setClaimContent(esMess.getClaim());
  1135. dto.setClaim(esMess.getClaim().get(0).getTextContent());
  1136. }
  1137. }
  1138. return dto;
  1139. }
  1140. /**
  1141. * 装载摘要附图
  1142. *
  1143. * @param patentColumnDTOS
  1144. * @return
  1145. */
  1146. public List<PatentColumnDTO> loadCoulumnDTO(List<PatentColumnDTO> patentColumnDTOS) {
  1147. patentColumnDTOS.forEach(item -> {
  1148. item.setPictureGuid(FormatUtil.getPictureFormat(item.getAppNo()));
  1149. });
  1150. return patentColumnDTOS;
  1151. }
  1152. /**
  1153. * 根据专利号查询出其他专利号
  1154. *
  1155. * @param patentNos
  1156. * @return
  1157. * @throws IOException
  1158. */
  1159. public SelectClaimDTO selectPatentNo(List<String> patentNos) throws IOException {
  1160. SearchRequest.Builder builder = new SearchRequest.Builder();
  1161. //设置查询索引
  1162. builder.index("patent");
  1163. List<Query> queryList = new ArrayList<>();
  1164. for (String patentNo : patentNos) {
  1165. Query q1 = QueryBuilders.term(t -> t.field("patent_no.keyword").value(patentNo));
  1166. queryList.add(q1);
  1167. }
  1168. //申请号
  1169. Query query = QueryBuilders.bool(i -> i.mustNot(queryList));
  1170. builder.query(query);
  1171. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  1172. SelectClaimDTO dto = new SelectClaimDTO();
  1173. List<Hit<Patent>> hits = response.hits().hits();
  1174. long value = response.hits().total().value();
  1175. if (value > 1) {
  1176. System.out.println("====================" + value);
  1177. }
  1178. return dto;
  1179. }
  1180. public PatentFamilyMessageWithId queryPatentFamily(Patent patent, String type) throws Exception {
  1181. //查询该专利是否已有同族
  1182. SearchRequest.Builder builderPatent = new SearchRequest.Builder();
  1183. //设置查询索引
  1184. builderPatent.index("patent_family");
  1185. //申请号
  1186. List<Query> queries = new ArrayList<>();
  1187. if (patent.getAppNo() != null && !patent.getAppNo().equals("")) {
  1188. Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getAppNo()));
  1189. //公开号
  1190. Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(patent.getAppNo()));
  1191. //授权号
  1192. Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(patent.getAppNo()));
  1193. //类型
  1194. queries.add(q1);
  1195. queries.add(q2);
  1196. queries.add(q3);
  1197. }
  1198. if (patent.getPublicNo() != null && !patent.getPublicNo().equals("")) {
  1199. Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getPublicNo()));
  1200. //公开号
  1201. Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(patent.getPublicNo()));
  1202. //授权号
  1203. Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(patent.getPublicNo()));
  1204. queries.add(q1);
  1205. queries.add(q2);
  1206. queries.add(q3);
  1207. }
  1208. if (patent.getGrantNo() != null && !patent.getGrantNo().equals("")) {
  1209. Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getGrantNo()));
  1210. //公开号
  1211. Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(patent.getGrantNo()));
  1212. //授权号
  1213. Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(patent.getGrantNo()));
  1214. queries.add(q1);
  1215. queries.add(q2);
  1216. queries.add(q3);
  1217. }
  1218. Query q4 = QueryBuilders.term(t -> t.field("family_type").value(type));
  1219. Query p = QueryBuilders.bool(i -> i.should(queries));
  1220. Query bool = QueryBuilders.bool(i -> i.must(q4, p));
  1221. builderPatent.query(bool);
  1222. SearchResponse<PatentFamilyMessage> response = client.search(builderPatent.build(), PatentFamilyMessage.class);
  1223. long total = response.hits().total().value();
  1224. if (total > 0) {
  1225. List<FamilyPatent> list = new ArrayList<>();
  1226. List<Hit<PatentFamilyMessage>> hits = response.hits().hits();
  1227. Hit<PatentFamilyMessage> hit = hits.get(0);
  1228. String id = hit.id();
  1229. PatentFamilyMessageWithId patentFamilyMessageWithId = new PatentFamilyMessageWithId();
  1230. patentFamilyMessageWithId.setId(id);
  1231. patentFamilyMessageWithId.setPatentFamilyMessage(hit.source());
  1232. return patentFamilyMessageWithId;
  1233. }
  1234. return null;
  1235. }
  1236. //根据父id获取相应专利的专利号
  1237. public List<String> getPatentNos(List<String> ids) throws IOException {
  1238. SearchRequest.Builder builder = new SearchRequest.Builder();
  1239. //设置查询索引
  1240. builder.index("patent");
  1241. Query q = QueryBuilders.ids(i -> i.values(ids));
  1242. builder.size(9999);
  1243. builder.query(q);
  1244. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  1245. List<Hit<Patent>> hits = response.hits().hits();
  1246. List<String> list = new ArrayList<>();
  1247. for (Hit<Patent> hit : hits) {
  1248. Patent patent = hit.source();
  1249. list.add(patent.getPatentNo());
  1250. }
  1251. return list;
  1252. }
  1253. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
  1254. public Boolean deletePatents(EsCustomFieldBatchVO vo) throws Exception {
  1255. Integer projectId = vo.getProjectId();
  1256. Integer startNum = vo.getStartNumber();
  1257. Integer endNum = vo.getEndNumber();
  1258. List<String> isAdd = vo.getIsAdd();
  1259. List<String> isDel = vo.getIsDelete();
  1260. if (!CollectionUtils.isEmpty(isAdd) && startNum <= 1 && endNum < 1) {
  1261. isAdd.removeAll(isDel);
  1262. for (String patentNo : isAdd) {
  1263. Integer number = this.getPatent(patentNo, projectId);
  1264. if (number < 1) {
  1265. throw new XiaoShiException("删除失败");
  1266. }
  1267. }
  1268. } else if (startNum >= 1 && endNum > 0) {
  1269. List<String> patentNos = esCustomFieldService.getPatentNos(vo);
  1270. for (String patentNo : patentNos) {
  1271. Integer number = this.getPatent(patentNo, projectId);
  1272. if (number < 1) {
  1273. throw new XiaoShiException("删除失败");
  1274. }
  1275. }
  1276. }
  1277. return true;
  1278. }
  1279. public Integer getPatent(String patentNo, Integer projectId) throws IOException {
  1280. SearchRequest.Builder builder = new SearchRequest.Builder();
  1281. //设置查询索引
  1282. builder.index("patent");
  1283. Query query = QueryBuilders.term(i -> i.field("project_id").value(projectId));
  1284. Query q = QueryBuilders.term(i -> i.field("patent_no.keyword").value(patentNo));
  1285. Query query1 = QueryBuilders.hasParent(i -> i.parentType("patent").query(q));
  1286. Query bool = QueryBuilders.bool(i -> i.must(query, query1));
  1287. builder.query(bool);
  1288. //解除最大条数限制
  1289. builder.trackTotalHits(i -> i.enabled(true));
  1290. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  1291. List<Hit<Patent>> hits = response.hits().hits();
  1292. List<String> list = new ArrayList<>();
  1293. for (Hit<Patent> hit : hits) {
  1294. String id = hit.id();
  1295. list.add(id);
  1296. }
  1297. return this.deleteByIds(list);
  1298. }
  1299. public Integer deleteByIds(List<String> ids) {
  1300. Query query = QueryBuilders.ids(n -> n.values(ids));
  1301. DeleteByQueryRequest request = DeleteByQueryRequest.of(i -> i.index("patent").query(query)
  1302. .refresh(true));
  1303. try {
  1304. client.deleteByQuery(request);
  1305. return 1;
  1306. } catch (IOException e) {
  1307. throw new XiaoShiException("删除失败");
  1308. }
  1309. }
  1310. /**
  1311. * 装载条件
  1312. *
  1313. * @param queryRequest
  1314. * @return
  1315. */
  1316. public EsPatentCommonVO tranPatentRequestToComVO(QueryRequest queryRequest) {
  1317. StringRequest stringRequest = (StringRequest) queryRequest;
  1318. EsPatentCommonVO commonVO = new EsPatentCommonVO();
  1319. try {
  1320. Integer taskId = stringRequest.getTaskId();
  1321. Integer projectId = stringRequest.getProjectId();
  1322. Integer productId = stringRequest.getProductId();
  1323. Long current = stringRequest.getCurrent();
  1324. Long size = stringRequest.getSize();
  1325. String productFrom = stringRequest.getFrom();
  1326. String searchCondition = stringRequest.getSearchQuery();
  1327. String groupField = stringRequest.getGroupField();
  1328. //判断同族分组
  1329. String str = "";
  1330. if (StringUtils.isNotEmpty(groupField)) {
  1331. switch (groupField) {
  1332. case "simpleFamilyId":
  1333. str = "simple_family_id";
  1334. break;
  1335. case "inpadocFamilyId":
  1336. str = "inpadoc_family_id";
  1337. break;
  1338. case "patsnapFamilyId":
  1339. str = "patsnap_family_id";
  1340. break;
  1341. }
  1342. }
  1343. String esField = str;
  1344. commonVO.setTaskId(taskId);
  1345. commonVO.setProjectId(projectId);
  1346. commonVO.setProductId(productId);
  1347. commonVO.setSearchCondition(searchCondition);
  1348. commonVO.setProductFrom(productFrom);
  1349. commonVO.setCurrent(current);
  1350. commonVO.setSize(size);
  1351. commonVO.setEsField(esField);
  1352. commonVO.setCustomFields(stringRequest.getCustomFields());
  1353. commonVO.setOrderDTOList(stringRequest.getOrderDTOList());
  1354. } catch (Exception e) {
  1355. }
  1356. return commonVO;
  1357. }
  1358. }