EsService.java 58 KB

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