EsService.java 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. package cn.cslg.pas.service.business.es;
  2. import cn.cslg.pas.common.core.base.IfConstant;
  3. import cn.cslg.pas.common.dto.PatentColumnDTO;
  4. import cn.cslg.pas.common.dto.PatentDTO;
  5. //import cn.cslg.pas.common.dto.business.EsPatentFamilyDTO;
  6. import cn.cslg.pas.common.dto.PatentStarListDTO;
  7. import cn.cslg.pas.common.dto.business.ContentDetailDTO;
  8. import cn.cslg.pas.common.dto.business.EsPatentFamilyDTO;
  9. import cn.cslg.pas.common.dto.business.SelectClaimDTO;
  10. import cn.cslg.pas.common.dto.es.EsCustomFieldValueDTO;
  11. import cn.cslg.pas.common.model.request.MapRequest;
  12. import cn.cslg.pas.common.model.request.OrderDTO;
  13. import cn.cslg.pas.common.model.request.QueryRequest;
  14. import cn.cslg.pas.common.model.request.StringRequest;
  15. import cn.cslg.pas.common.utils.FormatUtil;
  16. import cn.cslg.pas.common.utils.parseQueryToTree.expressManager;
  17. import cn.cslg.pas.common.utils.parseQueryToTree.operateNode;
  18. import cn.cslg.pas.common.utils.parseQueryToTree.treeNode;
  19. import cn.cslg.pas.common.vo.*;
  20. import cn.cslg.pas.domain.es.*;
  21. import cn.cslg.pas.exception.XiaoShiException;
  22. import cn.cslg.pas.service.business.CommonService;
  23. import cn.cslg.pas.service.common.PatentStarApiService;
  24. import cn.cslg.pas.service.query.FormatQueryService;
  25. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  26. import co.elastic.clients.elasticsearch._types.*;
  27. import co.elastic.clients.elasticsearch._types.aggregations.*;
  28. import co.elastic.clients.elasticsearch._types.query_dsl.*;
  29. import co.elastic.clients.elasticsearch.core.*;
  30. import co.elastic.clients.elasticsearch.core.search.Hit;
  31. import co.elastic.clients.json.JsonData;
  32. import com.alibaba.fastjson.JSON;
  33. import com.alibaba.fastjson.JSONArray;
  34. import com.alibaba.fastjson2.JSONObject;
  35. import lombok.RequiredArgsConstructor;
  36. import org.apache.commons.lang3.StringUtils;
  37. import org.elasticsearch.client.RequestOptions;
  38. import org.springframework.beans.BeanUtils;
  39. import org.springframework.beans.factory.annotation.Autowired;
  40. import org.springframework.context.annotation.Lazy;
  41. import org.springframework.stereotype.Service;
  42. import org.springframework.util.CollectionUtils;
  43. import java.io.IOException;
  44. import java.text.SimpleDateFormat;
  45. import java.util.*;
  46. @Service
  47. @RequiredArgsConstructor(onConstructor_ = {@Lazy})
  48. public class EsService {
  49. public final List<String> dateList = Arrays.asList("AD", "PD", "GD", "EXD", "PAD", "PED", "PPD", "EPD");
  50. private final ElasticsearchClient client;
  51. @Autowired
  52. private FormatQueryService formatQueryService;
  53. @Autowired
  54. private PatentStarApiService patentStarApiService;
  55. @Autowired
  56. private EsPatentService esPatentService;
  57. /**
  58. * @param patent
  59. * @throws Exception
  60. */
  61. public String addPatent(Patent patent) throws Exception {
  62. IndexResponse indexResponse = client.index(i -> i
  63. .index("patent")
  64. //传入user对象
  65. .document(patent)
  66. );
  67. return indexResponse.id();
  68. }
  69. /**
  70. * @param patent
  71. * @throws Exception
  72. */
  73. public String addChildPatent(Patent patent, String id) throws Exception {
  74. IndexResponse indexResponse = client.index(i -> i
  75. .index("patent")
  76. .routing(id)
  77. //传入user对象
  78. .document(patent)
  79. );
  80. return indexResponse.id();
  81. }
  82. /**
  83. * 根据专利号获取专利id
  84. *
  85. * @param patentNo
  86. * @return
  87. * @throws Exception
  88. */
  89. public PatentWithIdVO getIdByPatentNo(String patentNo) throws Exception {
  90. SearchRequest.Builder builder = new SearchRequest.Builder();
  91. //设置查询索引
  92. builder.index("patent");
  93. PatentWithIdVO patentWithIdVO = null;
  94. String id = null;
  95. Query q1 = QueryBuilders.term(t -> t.field("app_no.keyword").value(patentNo));
  96. //公开号
  97. Query q2 = QueryBuilders.term(t -> t.field("public_no.keyword").value(patentNo));
  98. //授权号
  99. Query q3 = QueryBuilders.term(t -> t.field("grant_no.keyword").value(patentNo));
  100. Query query = QueryBuilders.bool(i -> i.should(q1, q2, q3));
  101. builder.query(query);
  102. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  103. List<Hit<Patent>> hits = response.hits().hits();
  104. if (hits != null && hits.size() > 0) {
  105. id = hits.get(0).id();
  106. Patent patent = hits.get(0).source();
  107. patentWithIdVO = new PatentWithIdVO();
  108. patentWithIdVO.setPatent(patent);
  109. patentWithIdVO.setId(id);
  110. }
  111. return patentWithIdVO;
  112. }
  113. /**
  114. * Es检索
  115. *
  116. * @param queryRequest 检索条件
  117. * @return
  118. */
  119. public PatentDTO esSearch(QueryRequest queryRequest) throws Exception {
  120. PatentDTO dto = new PatentDTO();
  121. Integer taskId = queryRequest.getTaskId();
  122. String searchCondition = "";
  123. Integer projectId = queryRequest.getProjectId();
  124. Integer productId = queryRequest.getProductId();
  125. String productFrom = queryRequest.getFrom();
  126. Long current = queryRequest.getCurrent();
  127. Long size = queryRequest.getSize();
  128. String groupField = queryRequest.getGroupField();
  129. //判断表达式
  130. if (queryRequest instanceof StringRequest) {
  131. searchCondition = ((StringRequest) queryRequest).getSearchQuery();
  132. } else if (queryRequest instanceof MapRequest) {
  133. Map<String, Object> map = ((MapRequest) queryRequest).getSearchQuery();
  134. StringBuilder stringBuilder = new StringBuilder();
  135. for (String key : map.keySet()) {
  136. Object value = map.get(key);
  137. if (!"".contentEquals(stringBuilder)) {
  138. stringBuilder = stringBuilder.append(" AND ").append(key).append("=").append(value);
  139. } else {
  140. stringBuilder = stringBuilder.append(key).append("=").append(value);
  141. }
  142. }
  143. searchCondition = stringBuilder.toString();
  144. }
  145. List<EsCustomFieldValueDTO> customFields = queryRequest.getCustomFields();
  146. if (!CollectionUtils.isEmpty(customFields)) {
  147. searchCondition = this.parseCustomField(customFields);
  148. }
  149. if (taskId != null) {
  150. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  151. searchCondition = "taskId = " + taskId + " AND " + searchCondition;
  152. } else {
  153. searchCondition = "taskId = " + taskId;
  154. }
  155. } else {
  156. if (StringUtils.isNotEmpty(productFrom)) {
  157. if (productId != null) {
  158. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  159. searchCondition = "productId = " + productId + " AND " + searchCondition;
  160. } else {
  161. searchCondition = "productId = " + productId;
  162. }
  163. }
  164. } else {
  165. if (projectId != null) {
  166. if (searchCondition != null && !"".equals(searchCondition.trim())) {
  167. searchCondition = "projectId = " + projectId + " AND " + searchCondition;
  168. } else {
  169. searchCondition = "projectId = " + projectId;
  170. }
  171. }
  172. }
  173. }
  174. SearchRequest.Builder builder = new SearchRequest.Builder();
  175. //设置查询索引
  176. builder.index("patent");
  177. //1. 解析检索条件
  178. treeNode tree = expressManager.getInstance().Parse(searchCondition, false);
  179. //格式化检索式
  180. //3. 从es中检索数据
  181. Query q = formatQueryService.EsQueryToQuery((operateNode) tree, "patent");
  182. //判断同族分组
  183. String str = "";
  184. if (StringUtils.isNotEmpty(groupField)) {
  185. switch (groupField) {
  186. case "simpleFamilyId":
  187. str = "simple_family_id";
  188. break;
  189. case "inpadocFamilyId":
  190. str = "inpadoc_family_id";
  191. break;
  192. case "patsnapFamilyId":
  193. str = "patsnap_family_id";
  194. break;
  195. }
  196. }
  197. String esField = str;
  198. if (StringUtils.isNotEmpty(esField)) {
  199. List<SortOptions> options = new ArrayList<>();
  200. SortOptions appDate = SortOptions.of(i -> i.field(j -> j.field("app_date").order(SortOrder.Asc)));
  201. options.add(appDate);
  202. Aggregation hits = AggregationBuilders.topHits(i -> i.size(1).sort(options));
  203. Aggregation aggregation = new Aggregation.Builder().terms(new TermsAggregation.Builder()
  204. .field(esField).build())
  205. .aggregations(new HashMap() {{
  206. put("hitAgg", hits);
  207. }}).build();
  208. Aggregation filtersAgg = new Aggregation.Builder().filters(new FiltersAggregation.Builder()
  209. .filters(i -> i.array(Arrays.asList(q))).build())
  210. .aggregations(new HashMap() {{
  211. put("filtersAgg", aggregation);
  212. }}).build();
  213. builder.aggregations("Agg", filtersAgg);
  214. } else {
  215. //4. 返回数据
  216. builder.query(q);
  217. }
  218. //排序
  219. List<OrderDTO> dtoList = queryRequest.getOrderDTOList();
  220. if (!CollectionUtils.isEmpty(dtoList)) {
  221. String json = CommonService.readJsonFile("patent.json");
  222. List<EsConfigVO> esConfigVOS = JSON.parseArray(json, EsConfigVO.class);
  223. for (OrderDTO orderDTO : dtoList) {
  224. EsConfigVO configVO = esConfigVOS.stream().filter(item -> item.getField().equals(orderDTO.getOrderBy())).findFirst().orElse(null);
  225. if (configVO != null) {
  226. if (orderDTO.getOrderType().equals(IfConstant.NO)) {
  227. builder.sort(sortOptionsBuilder -> sortOptionsBuilder
  228. .field(fieldSortBuilder -> fieldSortBuilder
  229. .field(configVO.getEsField()).order(SortOrder.Asc)));
  230. } else {
  231. builder.sort(sortOptionsBuilder -> sortOptionsBuilder
  232. .field(fieldSortBuilder -> fieldSortBuilder
  233. .field(configVO.getEsField()).order(SortOrder.Desc)));
  234. }
  235. }
  236. }
  237. } else {
  238. builder.sort(sortOptionsBuilder -> sortOptionsBuilder
  239. .field(fieldSortBuilder -> fieldSortBuilder
  240. .field("patent_no.keyword").order(SortOrder.Desc)));
  241. }
  242. //分页
  243. if (current != null && size != null && current > 0 && size > 0) {
  244. builder.from((current.intValue() - 1) * size.intValue()).size(size.intValue());
  245. }
  246. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  247. List<PatentColumnDTO> list = new ArrayList<>();
  248. long total = 0L;
  249. if (StringUtils.isNotEmpty(esField)) {
  250. Aggregate agg = response.aggregations().get("Agg");
  251. List<FiltersBucket> buckets = agg.filters().buckets().array();
  252. for (FiltersBucket bucket : buckets) {
  253. Aggregate filtersAgg = bucket.aggregations().get("filtersAgg");
  254. List<StringTermsBucket> termsBuckets = filtersAgg.sterms().buckets().array();
  255. for (StringTermsBucket termsBucket : termsBuckets) {
  256. Aggregate hitAgg = termsBucket.aggregations().get("hitAgg");
  257. total = hitAgg.topHits().hits().total().value();
  258. List<Hit<JsonData>> hits = hitAgg.topHits().hits().hits();
  259. hits.forEach(hit -> {
  260. JsonData data = hit.source();
  261. Patent patent1 = JSONObject.parseObject(String.valueOf(data), Patent.class);
  262. PatentColumnDTO columnDTO = new PatentColumnDTO();
  263. BeanUtils.copyProperties(patent1, columnDTO);
  264. columnDTO.setApplicant(esPatentService.loadName(patent1.getApplicant()));
  265. columnDTO.setRightHolder(esPatentService.loadName(patent1.getRightHolder()));
  266. columnDTO.setInventor(esPatentService.loadName(patent1.getInventor()));
  267. list.add(columnDTO);
  268. });
  269. }
  270. }
  271. } else {
  272. List<Hit<Patent>> hits = response.hits().hits();
  273. total = response.hits().total().value();
  274. for (Hit<Patent> hit : hits) {
  275. Patent esMess = hit.source();
  276. PatentColumnDTO columnDTO = new PatentColumnDTO();
  277. // columnDTO.setPatentNo(esMess.getPatentNo());
  278. BeanUtils.copyProperties(esMess, columnDTO);
  279. columnDTO.setApplicant(esPatentService.loadName(esMess.getApplicant()));
  280. columnDTO.setRightHolder(esPatentService.loadName(esMess.getRightHolder()));
  281. columnDTO.setInventor(esPatentService.loadName(esMess.getInventor()));
  282. list.add(columnDTO);
  283. }
  284. }
  285. this.loadCoulumnDTO(list);
  286. dto.setTotal(total);
  287. dto.setPatents(list);
  288. dto.setPageNum(current);
  289. dto.setPageSize(size);
  290. return dto;
  291. }
  292. /**
  293. * 解析自定义栏位和值
  294. *
  295. * @param customFields
  296. * @return
  297. */
  298. public String parseCustomField(List<EsCustomFieldValueDTO> customFields) {
  299. int m = 1;
  300. int n = 0;
  301. StringBuilder builder = new StringBuilder();
  302. long start = System.currentTimeMillis();
  303. if (customFields.size() > m) {
  304. for (int i = 0; i < customFields.size(); i++) {
  305. EsCustomFieldValueDTO customField = customFields.get(i);
  306. if (i != n) {
  307. builder.append(" ").append("and").append(" ").append("(");
  308. this.appendStr(customField, builder, m, customField.getIfHaveChild());
  309. } else {
  310. builder.append("(");
  311. this.appendStr(customField, builder, m, customField.getIfHaveChild());
  312. }
  313. }
  314. } else {
  315. for (int i = 0; i < customFields.size(); i++) {
  316. EsCustomFieldValueDTO customField = customFields.get(i);
  317. if (i != n) {
  318. builder.append(" ").append("and").append(" ");
  319. this.appendStr(customField, builder, m, customField.getIfHaveChild());
  320. } else {
  321. builder.append("(");
  322. this.appendStr(customField, builder, m, customField.getIfHaveChild());
  323. }
  324. }
  325. }
  326. long end = System.currentTimeMillis();
  327. System.out.println("耗时" + (end - start));
  328. return builder.toString();
  329. }
  330. public void appendStr(EsCustomFieldValueDTO customField, StringBuilder builder, int m, boolean ifHaveChild) {
  331. builder.append("field").append("=").append(customField.getFieldId());
  332. List<String> values = customField.getFieldValue();
  333. if (!CollectionUtils.isEmpty(values)) {
  334. builder.append(" ").append("and").append(" ");
  335. if (ifHaveChild) {
  336. builder.append("statsValue").append("=");
  337. } else {
  338. builder.append("fieldValue").append("=");
  339. }
  340. if (values.size() > m) {
  341. builder.append("(");
  342. for (int j = 0; j < values.size(); j++) {
  343. String s = values.get(j);
  344. if (j != values.size() - m) {
  345. builder.append(s).append(" ").append("or").append(" ");
  346. } else {
  347. builder.append(s).append(")").append(")");
  348. }
  349. }
  350. } else {
  351. for (String value : values) {
  352. builder.append(value).append(")");
  353. }
  354. }
  355. } else {
  356. builder.append(")");
  357. }
  358. }
  359. /**
  360. * @param key
  361. * @param page
  362. * @param limit
  363. * @return
  364. */
  365. public List<Patent> search(String key, Integer page, Integer limit) throws IOException {
  366. SearchRequest.Builder builder = new SearchRequest.Builder();
  367. //设置查询索引
  368. builder.index("patent");
  369. //组装查询条件
  370. BoolQuery.Builder boolQuery = new BoolQuery.Builder();
  371. boolQuery.should(q -> q.match(v -> v
  372. .query(key)
  373. //字段名
  374. .field("patent_no")
  375. ));
  376. //多字段匹配
  377. // boolQuery.should(q -> q.matchPhrasePrefix(m -> m.query(key).field("content")));
  378. builder.query(q -> q.bool(boolQuery.build()));
  379. //分页
  380. if (page != null && limit != null) {
  381. builder.from(page).size(limit);
  382. }
  383. //排序
  384. // builder.sort(sortOptionsBuilder -> sortOptionsBuilder
  385. // .field(fieldSortBuilder -> fieldSortBuilder
  386. // .field("createTime").order(SortOrder.Desc)));
  387. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  388. List<Patent> list = new ArrayList<>();
  389. List<Hit<Patent>> hits = response.hits().hits();
  390. for (Hit<Patent> hit : hits) {
  391. Patent esMess = hit.source();
  392. list.add(esMess);
  393. }
  394. return list;
  395. }
  396. //更新patent
  397. public Integer updatePatent(Patent patent, String id) {
  398. UpdateRequest<Patent, Patent> req;
  399. req = UpdateRequest.of(
  400. b -> b.index("patent").id(id)
  401. .doc(patent)
  402. );
  403. try {
  404. client.update(req, Patent.class);
  405. return 1;
  406. } catch (IOException e) {
  407. return -1;
  408. }
  409. }
  410. //更新patent
  411. public Integer updatePatentShouldWait(Patent patent, String id) {
  412. UpdateRequest<Patent, Patent> req;
  413. req = UpdateRequest.of(
  414. b -> b.index("patent").id(id)
  415. .doc(patent).refresh(Refresh.True).waitForActiveShards(WaitForActiveShards.of(i -> i.count(1)))
  416. );
  417. try {
  418. client.update(req, Patent.class);
  419. return 1;
  420. } catch (IOException e) {
  421. return -1;
  422. }
  423. }
  424. //更新patent
  425. public Integer updatePatentById(Patent patent, String id) {
  426. UpdateRequest<Patent, Patent> req;
  427. req = UpdateRequest.of(
  428. b -> b.index("patent").id(id)
  429. .doc(patent));
  430. try {
  431. client.update(req, Patent.class);
  432. return 1;
  433. } catch (IOException e) {
  434. return -1;
  435. }
  436. }
  437. /*POST /patent/_update_by_query
  438. {
  439. "script": {
  440. "source": "ctx._source.project_id = 1",
  441. "lang": "painless"
  442. },
  443. "query": {
  444. "term": {
  445. "_id": "yYVNzowBmzIo81_44OnV"
  446. }
  447. }
  448. }*/
  449. //更新子文档
  450. public Integer updateByQuery(Patent patent, String id) throws IOException {
  451. ESCustomField customField = patent.getESCustomField();
  452. String valueField = "[";
  453. List<String> fieldValueList = customField.getFieldValue();
  454. if (!CollectionUtils.isEmpty(fieldValueList)) {
  455. int lastSum = fieldValueList.size() - 1;
  456. for (int i = 0; i < fieldValueList.size(); i++) {
  457. String s = fieldValueList.get(i);
  458. if (i == lastSum) {
  459. valueField = valueField + "\"" + s + "\"";
  460. } else {
  461. valueField = valueField + "\"" + s + "\"" + ",";
  462. }
  463. }
  464. }
  465. valueField = valueField + "]";
  466. String valueStats = "[";
  467. List<String> statsValueList = customField.getStatsValue();
  468. if (!CollectionUtils.isEmpty(statsValueList)) {
  469. int lastSum = statsValueList.size() - 1;
  470. for (int i = 0; i < statsValueList.size(); i++) {
  471. String s = statsValueList.get(i);
  472. if (i == lastSum) {
  473. valueStats = valueStats + "\"" + s + "\"";
  474. } else {
  475. valueStats = valueStats + "\"" + s + "\"" + ",";
  476. }
  477. }
  478. }
  479. valueStats = valueStats + "]";
  480. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  481. String s = format.format(customField.getCreateTime());
  482. String dateStr = "\'" + s + "\'";
  483. String projectId = "ctx._source.custom_field.project_id = " + customField.getProjectId() + ";";
  484. String field = "ctx._source.custom_field.field=" + customField.getField() + ";";
  485. String fieldType = "ctx._source.custom_field.field_type = " + customField.getFieldType() + ";";
  486. String personId = "ctx._source.custom_field.person_id = " + customField.getPersonId() + ";";
  487. String createTime = "ctx._source.custom_field.create_time = " + dateStr + ";";
  488. String fieldValue = "ctx._source.custom_field.field_value = " + valueField + ";";
  489. String statsValue = "ctx._source.custom_field.stats_value = " + valueStats;
  490. String source = projectId + field + fieldType + personId + createTime + fieldValue + statsValue;
  491. InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").source(source));
  492. Script script = Script.of(i -> i.inline(inlineScript));
  493. Query query = QueryBuilders.term(i -> i.field("_id").value(id));
  494. UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).query(query));
  495. try {
  496. client.updateByQuery(request);
  497. return 1;
  498. } catch (IOException e) {
  499. return -1;
  500. }
  501. }
  502. /**
  503. * @param key
  504. * @param page
  505. * @param limit
  506. * @return
  507. * @throws IOException
  508. */
  509. public List<Patent> searchChild(String key, Integer page, Integer limit) throws IOException {
  510. SearchRequest.Builder builder = new SearchRequest.Builder();
  511. //设置查询索引
  512. builder.index("patent");
  513. //组装查询条件
  514. HasChildQuery.Builder hasChildQuery = new HasChildQuery.Builder();
  515. hasChildQuery.type("project");
  516. hasChildQuery.query(q -> q.match(m -> m
  517. .query(key)
  518. //字段名
  519. .field("project_id")
  520. ));
  521. builder.query(q -> q.hasChild(hasChildQuery.build()));
  522. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  523. List<Patent> list = new ArrayList<>();
  524. List<Hit<Patent>> hits = response.hits().hits();
  525. for (Hit<Patent> hit : hits) {
  526. Patent esMess = hit.source();
  527. list.add(esMess);
  528. }
  529. return list;
  530. }
  531. /**
  532. * 查询是否存在专利
  533. *
  534. * @param parentId
  535. * @param projectId
  536. * @return
  537. */
  538. public Boolean searchPatent(String parentId, Integer projectId) throws IOException {
  539. boolean flag = false;
  540. SearchRequest.Builder builder = new SearchRequest.Builder();
  541. //设置查询索引
  542. builder.index("patent");
  543. Query q1 = QueryBuilders.term(t -> t.field("project_id").value(projectId));
  544. Query q2 = QueryBuilders.parentId(parent -> parent.type("project").id(parentId));
  545. Query bool = QueryBuilders.bool(i -> i.must(q1, q2));
  546. builder.query(bool);
  547. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  548. long total = response.hits().total().value();
  549. if (total > 0) {
  550. flag = true;
  551. }
  552. return flag;
  553. }
  554. /**
  555. * 查询是否存在专利
  556. *
  557. * @param parentId
  558. * @param projectId
  559. * @return
  560. */
  561. public Boolean ifInTask(String parentId, Integer projectId, Integer taskId) throws IOException {
  562. boolean flag = false;
  563. SearchRequest.Builder builder = new SearchRequest.Builder();
  564. //设置查询索引
  565. builder.index("patent");
  566. Query q1 = QueryBuilders.term(t -> t.field("import_task.project_id").value(projectId));
  567. Query q3 = QueryBuilders.term(t -> t.field("import_task.task_id").value(projectId));
  568. Query q2 = QueryBuilders.parentId(parent -> parent.type("import_task").id(parentId));
  569. Query bool = QueryBuilders.bool(i -> i.must(q1, q2, q3));
  570. builder.query(bool);
  571. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  572. long total = response.hits().total().value();
  573. if (total > 0) {
  574. flag = true;
  575. }
  576. return flag;
  577. }
  578. /**
  579. * 查询同族
  580. *
  581. * @param nos
  582. * @param type
  583. * @return
  584. * @throws IOException
  585. */
  586. public EsPatentFamilyDTO addEsPatentFamily(List<String> nos, String type) throws IOException {
  587. EsPatentFamilyDTO esDTO = new EsPatentFamilyDTO();
  588. List<String> absentList = new ArrayList<>();
  589. PatentFamilyMessage patentFamilyMessage = null;
  590. String id = "";
  591. //遍历,根据专利号查询同族
  592. for (String no : nos) {
  593. SearchRequest.Builder builder = new SearchRequest.Builder();
  594. //设置查询索引
  595. builder.index("patent_family");
  596. //申请号
  597. Query q1 = QueryBuilders.term(t -> t.field("app_no").value(no));
  598. //公开号
  599. Query q2 = QueryBuilders.term(t -> t.field("public_no").value(no));
  600. //授权号
  601. Query q3 = QueryBuilders.term(t -> t.field("grant_no").value(no));
  602. //类型
  603. Query q4 = QueryBuilders.term(t -> t.field("family_type").value(type));
  604. Query bool = QueryBuilders.bool(i -> i.must(q4).should(q1, q2, q3));
  605. builder.query(bool);
  606. SearchResponse<PatentFamilyMessage> response = client.search(builder.build(), PatentFamilyMessage.class);
  607. long total = response.hits().total().value();
  608. if (total > 0) {
  609. List<FamilyPatent> list = new ArrayList<>();
  610. List<Hit<PatentFamilyMessage>> hits = response.hits().hits();
  611. Hit<PatentFamilyMessage> hit = hits.get(0);
  612. id = hit.id();
  613. patentFamilyMessage = hit.source();
  614. break;
  615. }
  616. }
  617. List<String> notInNos = new ArrayList<>();
  618. //当查询到同族时
  619. if (patentFamilyMessage != null) {
  620. List<FamilyPatent> familyPatents = patentFamilyMessage.getPatent();
  621. for (String no : nos) {
  622. FamilyPatent familyPatent = familyPatents.stream()
  623. .filter(item -> item.getAppNo() != null && item.getAppNo().equals(no) ||
  624. item.getPublicNo() != null && item.getPublicNo().equals(no) ||
  625. item.getGrantNo() != null && item.getGrantNo().equals(no))
  626. .findFirst().orElse(null);
  627. if (familyPatent == null) {
  628. notInNos.add(no);
  629. }
  630. }
  631. }
  632. //当未查询到同族时
  633. else {
  634. patentFamilyMessage = new PatentFamilyMessage();
  635. patentFamilyMessage.setFamilyType(type);
  636. patentFamilyMessage.setPatent(new ArrayList<>());
  637. notInNos.addAll(nos);
  638. }
  639. if (notInNos.size() > 0) {
  640. //所有专利号的专利详情
  641. List<StarPatentVO> starPatents = new ArrayList<>();
  642. PatentStarListDTO patentStarListDTO = new PatentStarListDTO();
  643. List<PatentStarListDTO> patentStarListDtos = patentStarApiService.splitPatentNoByType(notInNos, patentStarListDTO);
  644. while (patentStarListDtos.size() > 0) {
  645. PatentStarListDTO patentStarListDTO1 = patentStarListDtos.remove(0);
  646. patentStarListDTO1.setPageNum(1);
  647. patentStarListDTO1.setRowCount(50);
  648. Map<String, Object> resultMap = patentStarApiService.patentStarSearchApi(patentStarListDTO1);
  649. if (resultMap == null || (Integer) resultMap.get("total") == 0) {
  650. continue;
  651. }
  652. starPatents.addAll((List<StarPatentVO>) resultMap.get("records"));
  653. }
  654. List<FamilyPatent> patents = new ArrayList<>();
  655. starPatents.forEach(item -> {
  656. FamilyPatent familyPatent = new FamilyPatent();
  657. familyPatent.setAppNo(item.getApplicationNo());
  658. familyPatent.setPublicNo(item.getPublicNo());
  659. familyPatent.setGrantNo(item.getPublicAccreditNo());
  660. patents.add(familyPatent);
  661. });
  662. patentFamilyMessage.getPatent().addAll(patents);
  663. //当id不为null时
  664. if (!id.equals("")) {
  665. this.updatePatentFamily(patentFamilyMessage, id);
  666. } else {
  667. try {
  668. id = this.addPatentFamily(patentFamilyMessage);
  669. } catch (Exception e) {
  670. }
  671. }
  672. }
  673. esDTO.setPatentFamilyId(id);
  674. esDTO.setFamilyNum(patentFamilyMessage.getPatent().size());
  675. return esDTO;
  676. }
  677. /**
  678. * 添加同族
  679. *
  680. * @param message
  681. * @return
  682. * @throws Exception
  683. */
  684. public String addPatentFamily(PatentFamilyMessage message) throws Exception {
  685. IndexResponse indexResponse = client.index(i -> i
  686. .index("patent_family")
  687. .document(message)
  688. );
  689. return indexResponse.id();
  690. }
  691. /**
  692. * 更新同族
  693. *
  694. * @param message
  695. * @param id
  696. * @return
  697. */
  698. public Integer updatePatentFamily(PatentFamilyMessage message, String id) {
  699. UpdateRequest<PatentFamilyMessage, PatentFamilyMessage> req;
  700. req = UpdateRequest.of(
  701. b -> b.index("patent_family")
  702. .id(id)
  703. .doc(message)
  704. );
  705. try {
  706. client.update(req, PatentFamilyMessage.class);
  707. return 1;
  708. } catch (IOException e) {
  709. return -1;
  710. }
  711. }
  712. /**
  713. * 更新专利事务
  714. *
  715. * @param
  716. * @param id
  717. * @return
  718. */
  719. public Integer updateLegalEvent(LegalEvent legalEvent, String id) {
  720. UpdateRequest<LegalEvent, LegalEvent> req;
  721. req = UpdateRequest.of(
  722. b -> b.index("legal_event")
  723. .id(id)
  724. .doc(legalEvent)
  725. );
  726. try {
  727. client.update(req, LegalEvent.class);
  728. return 1;
  729. } catch (IOException e) {
  730. return -1;
  731. }
  732. }
  733. /**
  734. * 添加法律事务
  735. *
  736. * @param
  737. * @return
  738. * @throws Exception
  739. */
  740. public String addLegalEvent(LegalEvent legalEvent) throws Exception {
  741. IndexResponse indexResponse = client.index(i -> i
  742. .index("legal_event")
  743. .document(legalEvent)
  744. );
  745. return indexResponse.id();
  746. }
  747. /**
  748. * 更新专利事务
  749. *
  750. * @param
  751. * @param id
  752. * @return
  753. */
  754. public Integer updateQuotePatent(PatentQuoteMessage patentQuoteMessage, String id) {
  755. UpdateRequest<PatentQuoteMessage, PatentQuoteMessage> req;
  756. req = UpdateRequest.of(
  757. b -> b.index("quote_patent")
  758. .id(id)
  759. .doc(patentQuoteMessage)
  760. );
  761. try {
  762. client.update(req, PatentQuoteMessage.class);
  763. return 1;
  764. } catch (IOException e) {
  765. return -1;
  766. }
  767. }
  768. /**
  769. * 添加法律事务
  770. *
  771. * @param
  772. * @return
  773. * @throws Exception
  774. */
  775. public String addQuotePatent(PatentQuoteMessage patentQuoteMessage) throws Exception {
  776. IndexResponse indexResponse = client.index(i -> i
  777. .index("quote_patent")
  778. .document(patentQuoteMessage)
  779. );
  780. return indexResponse.id();
  781. }
  782. public String addEsQuotePatent(String no, List<String> nos) throws Exception {
  783. StarPatentVO starPatentVO = patentStarApiService.getPatentByNo(no);
  784. if (starPatentVO == null) {
  785. return null;
  786. }
  787. QuotePatent quotePatent = this.reQuotePatent(starPatentVO);
  788. PatentQuoteMessage patentQuoteMessage = null;
  789. //根据申请号和
  790. String id = "";
  791. //根据专利号查询是否有引用信息
  792. SearchRequest.Builder builder = new SearchRequest.Builder();
  793. //设置查询索引
  794. builder.index("quote_patent");
  795. //申请号
  796. Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(starPatentVO.getApplicationNo()));
  797. Query bool = QueryBuilders.bool(i -> i.must(q1));
  798. builder.query(bool);
  799. SearchResponse<PatentQuoteMessage> response = client.search(builder.build(), PatentQuoteMessage.class);
  800. long total = response.hits().total().value();
  801. if (total > 0) {
  802. patentQuoteMessage = response.hits().hits().get(0).source();
  803. id = response.hits().hits().get(0).id();
  804. }
  805. List<QuotePatent> quotePatents = new ArrayList<>();
  806. if (patentQuoteMessage != null && patentQuoteMessage.getQuotedPatents() != null) {
  807. quotePatents = patentQuoteMessage.getQuotedPatents();
  808. }
  809. for (String patentNo : nos) {
  810. StarPatentVO starPatentVO1 = patentStarApiService.getPatentByNo(patentNo);
  811. QuotePatent quotePatent1 = null;
  812. if (quotePatents.size() > 0) {
  813. quotePatent1 = quotePatents.stream()
  814. .filter(item -> item.getAppNo().equals(starPatentVO1.getApplicationNo())).findFirst().orElse(null);
  815. }
  816. if (quotePatent1 == null) {
  817. quotePatent1 = this.reQuotePatent(starPatentVO1);
  818. quotePatents.add(quotePatent1);
  819. }
  820. }
  821. if (patentQuoteMessage == null) {
  822. if (quotePatents.size() != 0) {
  823. patentQuoteMessage = new PatentQuoteMessage();
  824. patentQuoteMessage.setPatent(quotePatent);
  825. patentQuoteMessage.setQuotedPatents(quotePatents);
  826. this.addQuotePatent(patentQuoteMessage);
  827. }
  828. } else {
  829. patentQuoteMessage.getQuotedPatents().addAll(quotePatents);
  830. this.updateQuotePatent(patentQuoteMessage, id);
  831. }
  832. return "";
  833. }
  834. private QuotePatent reQuotePatent(StarPatentVO starPatentVO) {
  835. QuotePatent quotePatent = new QuotePatent();
  836. //装载申请人
  837. if (starPatentVO.getApplicantStr() != null && !starPatentVO.getApplicantStr().equals("")) {
  838. List<String> names = Arrays.asList(starPatentVO.getApplicantStr().split(";"));
  839. List<PatentPerson> patentPeople = new ArrayList<>();
  840. for (int i = 0; i < names.size(); i++) {
  841. PatentPerson patentPerson = new PatentPerson();
  842. patentPerson.setOrder(i + 1);
  843. patentPerson.setType("1");
  844. patentPerson.setName(names.get(i));
  845. patentPeople.add(patentPerson);
  846. }
  847. quotePatent.setApplicant(patentPeople);
  848. }
  849. //装载权利人
  850. if (starPatentVO.getCurrentApplicantStr() != null && !starPatentVO.getCurrentApplicantStr().equals("")) {
  851. List<String> names = Arrays.asList(starPatentVO.getCurrentApplicantStr().split(";"));
  852. List<PatentPerson> patentPeople = new ArrayList<>();
  853. for (int i = 0; i < names.size(); i++) {
  854. PatentPerson patentPerson = new PatentPerson();
  855. patentPerson.setOrder(0);
  856. patentPerson.setType("1");
  857. patentPerson.setName(names.get(i));
  858. patentPeople.add(patentPerson);
  859. }
  860. quotePatent.setRightHolder(patentPeople);
  861. }
  862. quotePatent.setAppNo(starPatentVO.getApplicationNo());
  863. quotePatent.setGrantNo(starPatentVO.getPublicAccreditNo());
  864. quotePatent.setPublicNo(starPatentVO.getPublicNo());
  865. return quotePatent;
  866. }
  867. public String addEsLegalEvent(String patentNo) {
  868. LegalEvent legalEvent = null;
  869. String id = "";
  870. //根据专利号查询
  871. StarPatentVO starPatentVO = patentStarApiService.getPatentByNo(patentNo);
  872. if (starPatentVO == null) {
  873. return null;
  874. }
  875. String cnLegalApiStr = patentStarApiService.getCnLegalApi(starPatentVO.getRowApplicationNo());
  876. if (cnLegalApiStr != null && !cnLegalApiStr.equals("")) {
  877. List<LegalEvent> legalEvents = new ArrayList<>();
  878. //根据专利号查询是否有引用信息
  879. SearchRequest.Builder builder = new SearchRequest.Builder();
  880. //设置查询索引
  881. builder.index("legal_event");
  882. //申请号
  883. Query q1 = QueryBuilders.term(t -> t.field("app_no").value(starPatentVO.getApplicationNo()));
  884. Query q2 = QueryBuilders.term((t -> t.field("grant_no").value(starPatentVO.getPublicAccreditNo())));
  885. Query q3 = QueryBuilders.term((t -> t.field("public_no").value(starPatentVO.getPublicNo())));
  886. Query bool = QueryBuilders.bool(i -> i.should(q1, q2, q3));
  887. builder.query(bool);
  888. SearchResponse<LegalEvent> response = null;
  889. try {
  890. response = client.search(builder.build(), LegalEvent.class);
  891. } catch (IOException e) {
  892. e.printStackTrace();
  893. }
  894. long total = response.hits().total().value();
  895. if (total > 0) {
  896. response.hits().hits().forEach(item -> {
  897. legalEvents.add(item.source());
  898. });
  899. }
  900. List<ChinaLeagalStatus> chinaLeagalStatuses = JSON.parseArray(cnLegalApiStr, ChinaLeagalStatus.class);
  901. chinaLeagalStatuses.forEach(item -> {
  902. LegalEvent tem = legalEvents.stream().filter(em -> em.getEventDate() != null && em.getEventDate().compareTo(item.getLegalDate()) == 0).findFirst().orElse(null);
  903. if (tem == null) {
  904. LegalEvent legalEvent1 = new LegalEvent();
  905. legalEvent1.setEventDate(item.getLegalDate());
  906. legalEvent1.setCode(item.getLegalCode());
  907. legalEvent1.setAppNo(starPatentVO.getApplicationNo());
  908. legalEvent1.setGrantNo(starPatentVO.getPublicAccreditNo());
  909. legalEvent1.setPublicNo(starPatentVO.getPublicNo());
  910. legalEvent1.setDescription(item.getLegalStatusInfo());
  911. legalEvent1.setName(item.getLegalStatus());
  912. try {
  913. String reId =this.addLegalEvent(legalEvent1);
  914. System.out.println(reId);
  915. } catch (Exception e) {
  916. throw new XiaoShiException(e.getMessage());
  917. }
  918. }
  919. });
  920. }
  921. return "";
  922. }
  923. /**
  924. * 查询权利要求
  925. *
  926. * @param patentNo
  927. * @return
  928. */
  929. public SelectClaimDTO selectClaim(String patentNo) throws IOException {
  930. SearchRequest.Builder builder = new SearchRequest.Builder();
  931. //设置查询索引
  932. builder.index("patent");
  933. //原始数据
  934. Query q = QueryBuilders.term(t -> t.field("claim.if_origin").value(true));
  935. //申请号
  936. Query q1 = QueryBuilders.term(t -> t.field("app_no.keyword").value(patentNo));
  937. //公开号
  938. Query q2 = QueryBuilders.term(t -> t.field("public_no.keyword").value(patentNo));
  939. //授权号
  940. Query q3 = QueryBuilders.term(t -> t.field("grant_no.keyword").value(patentNo));
  941. Query query = QueryBuilders.bool(i -> i.should(q1, q2, q3));
  942. Query bool = QueryBuilders.bool(i -> i.must(q, query));
  943. builder.query(bool);
  944. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  945. SelectClaimDTO dto = new SelectClaimDTO();
  946. List<Hit<Patent>> hits = response.hits().hits();
  947. for (Hit<Patent> hit : hits) {
  948. Patent esMess = hit.source();
  949. if (esMess != null) {
  950. dto.setClaimContent(esMess.getClaim());
  951. String claim = StringUtils.strip(JSON.toJSONString(esMess.getClaim()), "[]");
  952. ContentDetailDTO contentDetailDTO = JSONObject.parseObject(claim, ContentDetailDTO.class);
  953. if (contentDetailDTO.getIfOrigin()) {
  954. dto.setClaim(contentDetailDTO.getTextContent().replaceAll("\t", ""));
  955. }
  956. }
  957. }
  958. return dto;
  959. }
  960. /**
  961. * 装载摘要附图
  962. *
  963. * @param patentColumnDTOS
  964. * @return
  965. */
  966. public List<PatentColumnDTO> loadCoulumnDTO(List<PatentColumnDTO> patentColumnDTOS) {
  967. patentColumnDTOS.forEach(item -> {
  968. item.setPictureGuid(FormatUtil.getPictureFormat(item.getAppNo()));
  969. });
  970. return patentColumnDTOS;
  971. }
  972. /**
  973. * 根据专利号查询出其他专利号
  974. *
  975. * @param patentNos
  976. * @return
  977. * @throws IOException
  978. */
  979. public SelectClaimDTO selectPatentNo(List<String> patentNos) throws IOException {
  980. SearchRequest.Builder builder = new SearchRequest.Builder();
  981. //设置查询索引
  982. builder.index("patent");
  983. List<Query> queryList = new ArrayList<>();
  984. for (String patentNo : patentNos) {
  985. Query q1 = QueryBuilders.term(t -> t.field("patent_no.keyword").value(patentNo));
  986. queryList.add(q1);
  987. }
  988. //申请号
  989. Query query = QueryBuilders.bool(i -> i.mustNot(queryList));
  990. builder.query(query);
  991. SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
  992. SelectClaimDTO dto = new SelectClaimDTO();
  993. List<Hit<Patent>> hits = response.hits().hits();
  994. long value = response.hits().total().value();
  995. if (value > 1) {
  996. System.out.println("====================" + value);
  997. }
  998. return dto;
  999. }
  1000. /**
  1001. * 更新合并申请人/权利人/发明人
  1002. *
  1003. * @param patent
  1004. * @param id
  1005. * @return
  1006. */
  1007. public Integer updateMergePerson(Patent patent, String id) {
  1008. UpdateRequest<Patent, Patent> req;
  1009. req = UpdateRequest.of(
  1010. b -> b.index("patent")
  1011. .id(id)
  1012. .doc(patent)
  1013. .docAsUpsert(true)
  1014. );
  1015. try {
  1016. client.update(req, Patent.class);
  1017. return 1;
  1018. } catch (IOException e) {
  1019. return -1;
  1020. }
  1021. }
  1022. /**
  1023. * 删除申请人/权利人/发明人合并名称
  1024. *
  1025. * @param patent
  1026. * @param id
  1027. * @return
  1028. */
  1029. public Integer delMergePerson(Patent patent, String id, Integer type, String name) {
  1030. String source = "";
  1031. if (type == 0) {
  1032. 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); }";
  1033. } else {
  1034. source = "if (ctx._source.merge_inventor != null) { ctx._source.merge_inventor.removeIf(item -> item.name == params.name); }";
  1035. }
  1036. String finalSource = source;
  1037. InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").params("name", JsonData.of(name)).source(finalSource));
  1038. Script script = Script.of(i -> i.inline(inlineScript));
  1039. Query query = QueryBuilders.term(i -> i.field("_id").value(id));
  1040. UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).query(query));
  1041. try {
  1042. client.updateByQuery(request);
  1043. return 1;
  1044. } catch (IOException e) {
  1045. return -1;
  1046. }
  1047. }
  1048. }