EsService.java 61 KB

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