EsService.java 59 KB

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