EsService.java 58 KB

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