12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478 |
- package cn.cslg.pas.service.business.es;
- import cn.cslg.pas.common.core.base.IfConstant;
- import cn.cslg.pas.common.dto.GetUnselectedDTO;
- import cn.cslg.pas.common.dto.PatentColumnDTO;
- import cn.cslg.pas.common.dto.PatentDTO;
- //import cn.cslg.pas.common.dto.business.EsPatentFamilyDTO;
- import cn.cslg.pas.common.dto.PatentStarListDTO;
- import cn.cslg.pas.common.dto.business.ContentDetailDTO;
- import cn.cslg.pas.common.dto.business.EsPatentFamilyDTO;
- import cn.cslg.pas.common.dto.business.SelectClaimDTO;
- import cn.cslg.pas.common.dto.es.EsCustomFieldDTO;
- import cn.cslg.pas.common.dto.es.EsCustomFieldValueDTO;
- import cn.cslg.pas.common.model.request.MapRequest;
- import cn.cslg.pas.common.model.request.OrderDTO;
- import cn.cslg.pas.common.model.request.QueryRequest;
- import cn.cslg.pas.common.model.request.StringRequest;
- import cn.cslg.pas.common.utils.FormatUtil;
- import cn.cslg.pas.common.utils.parseQueryToTree.expressManager;
- import cn.cslg.pas.common.utils.parseQueryToTree.operateNode;
- import cn.cslg.pas.common.utils.parseQueryToTree.treeNode;
- import cn.cslg.pas.common.vo.*;
- import cn.cslg.pas.common.vo.es.EsCustomFieldBatchVO;
- import cn.cslg.pas.common.vo.es.PatentFamilyMessageWithId;
- import cn.cslg.pas.domain.es.*;
- import cn.cslg.pas.exception.XiaoShiException;
- import cn.cslg.pas.service.business.CommonService;
- import cn.cslg.pas.service.common.PatentStarApiService;
- import cn.cslg.pas.service.query.FormatQueryService;
- import co.elastic.clients.elasticsearch.ElasticsearchClient;
- import co.elastic.clients.elasticsearch._types.*;
- import co.elastic.clients.elasticsearch._types.aggregations.*;
- import co.elastic.clients.elasticsearch._types.query_dsl.*;
- import co.elastic.clients.elasticsearch.core.*;
- import co.elastic.clients.elasticsearch.core.search.Hit;
- import co.elastic.clients.json.JsonData;
- import com.alibaba.fastjson.JSON;
- import com.rabbitmq.client.impl.nio.WriteRequest;
- import lombok.RequiredArgsConstructor;
- import org.apache.commons.lang3.ObjectUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Lazy;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.util.CollectionUtils;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.stream.Collectors;
- @Service
- @RequiredArgsConstructor(onConstructor_ = {@Lazy})
- public class EsService {
- public final List<String> dateList = Arrays.asList("AD", "PD", "GD", "EXD", "PAD", "PED", "PPD", "EPD");
- private final ElasticsearchClient client;
- @Autowired
- private FormatQueryService formatQueryService;
- @Autowired
- private PatentStarApiService patentStarApiService;
- @Autowired
- private EsPatentService esPatentService;
- @Lazy
- @Autowired
- private EsCountService esCountService;
- @Autowired
- private EsCustomFieldService esCustomFieldService;
- /**
- * @param patent
- * @throws Exception
- */
- public String addPatent(Patent patent) throws Exception {
- IndexResponse indexResponse = client.index(i -> i
- .index("patent")
- //传入user对象
- .document(patent)
- );
- return indexResponse.id();
- }
- /**
- * @param patent
- * @throws Exception
- */
- public String addChildPatent(Patent patent, String id) throws Exception {
- IndexResponse indexResponse = client.index(i -> i
- .index("patent")
- .routing(id)
- //传入user对象
- .document(patent).refresh(Refresh.True).waitForActiveShards(WaitForActiveShards.of(t -> t.count(1)))
- );
- return indexResponse.id();
- }
- /**
- * 根据专利号获取专利id
- *
- * @param patentNo
- * @return
- * @throws Exception
- */
- public PatentWithIdVO getIdByPatentNo(String patentNo) throws Exception {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- PatentWithIdVO patentWithIdVO = null;
- String id = null;
- Query q1 = QueryBuilders.term(t -> t.field("app_no.keyword").value(patentNo));
- //公开号
- Query q2 = QueryBuilders.term(t -> t.field("public_no.keyword").value(patentNo));
- //授权号
- Query q3 = QueryBuilders.term(t -> t.field("grant_no.keyword").value(patentNo));
- Query query = QueryBuilders.bool(i -> i.should(q1, q2, q3));
- builder.query(query);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<Hit<Patent>> hits = response.hits().hits();
- if (hits != null && hits.size() > 0) {
- id = hits.get(0).id();
- Patent patent = hits.get(0).source();
- patentWithIdVO = new PatentWithIdVO();
- patentWithIdVO.setPatent(patent);
- patentWithIdVO.setId(id);
- }
- return patentWithIdVO;
- }
- /**
- * Es检索
- *
- * @param queryRequest 检索条件
- * @return
- */
- public PatentDTO esSearch(QueryRequest queryRequest) throws Exception {
- PatentDTO dto = new PatentDTO();
- Integer taskId = queryRequest.getTaskId();
- String searchCondition = "";
- Integer projectId = queryRequest.getProjectId();
- Integer productId = queryRequest.getProductId();
- String productFrom = queryRequest.getFrom();
- Long current = queryRequest.getCurrent();
- Long size = queryRequest.getSize();
- String groupField = queryRequest.getGroupField();
- //判断表达式
- if (queryRequest instanceof StringRequest) {
- searchCondition = ((StringRequest) queryRequest).getSearchQuery();
- } else if (queryRequest instanceof MapRequest) {
- Map<String, Object> map = ((MapRequest) queryRequest).getSearchQuery();
- StringBuilder stringBuilder = new StringBuilder();
- for (String key : map.keySet()) {
- Object value = map.get(key);
- if (!"".contentEquals(stringBuilder)) {
- stringBuilder = stringBuilder.append(" AND ").append(key).append("=").append(value);
- } else {
- stringBuilder = stringBuilder.append(key).append("=").append(value);
- }
- }
- searchCondition = stringBuilder.toString();
- }
- List<EsCustomFieldValueDTO> customFields = queryRequest.getCustomFields();
- if (!CollectionUtils.isEmpty(customFields)) {
- String customFieldCondition = this.parseCustomField(customFields, projectId, taskId);
- if (StringUtils.isNotEmpty(searchCondition)) {
- searchCondition = searchCondition + " AND " + customFieldCondition;
- } else {
- searchCondition = customFieldCondition;
- }
- }
- String condition = this.appendIdsCondition(searchCondition, taskId, productFrom, projectId, productId);
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- //1. 解析检索条件
- treeNode tree = expressManager.getInstance().Parse(condition, false);
- //3. 从es中检索数据
- Query q = formatQueryService.EsQueryToQuery((operateNode) tree, "patent", projectId);
- builder.query(q);
- //判断同族分组
- String str = "";
- if (StringUtils.isNotEmpty(groupField)) {
- switch (groupField) {
- case "simpleFamilyId":
- str = "simple_family_id";
- break;
- case "inpadocFamilyId":
- str = "inpadoc_family_id";
- break;
- case "patsnapFamilyId":
- str = "patsnap_family_id";
- break;
- }
- }
- String esField = str;
- if (StringUtils.isNotEmpty(esField)) {
- List<SortOptions> options = new ArrayList<>();
- SortOptions appDate = SortOptions.of(i -> i.field(j -> j.field("app_date").order(SortOrder.Asc)));
- options.add(appDate);
- Aggregation bucketSort = AggregationBuilders.bucketSort(i -> i.from((current.intValue() - 1) * size.intValue()).size(size.intValue()));
- Aggregation aggregation = new Aggregation.Builder().terms(new TermsAggregation.Builder()
- .field(esField).size(100000).build())
- .aggregations(new HashMap() {{
- put("hitAgg", bucketSort);
- }}).build();
- builder.aggregations("Agg", aggregation);
- //对聚合结果统计出总数
- Aggregation terms = AggregationBuilders.terms(i -> i.field(esField).size(100000));
- builder.aggregations("termAgg", terms);
- BucketsPath bucketsPath = BucketsPath.of(i -> i.single("termAgg>_count"));
- Aggregation statsBucket = AggregationBuilders.statsBucket(i -> i.bucketsPath(bucketsPath));
- builder.aggregations("statsBucket", statsBucket);
- }
- //排序
- List<SortOptions> optionsList = new ArrayList<>();
- List<OrderDTO> dtoList = queryRequest.getOrderDTOList();
- if (!CollectionUtils.isEmpty(dtoList)) {
- String json = CommonService.readJsonFile("patent.json");
- List<EsConfigVO> esConfigVOS = JSON.parseArray(json, EsConfigVO.class);
- for (OrderDTO orderDTO : dtoList) {
- EsConfigVO configVO = esConfigVOS.stream().filter(item -> item.getField().equals(orderDTO.getOrderBy())).findFirst().orElse(null);
- if (configVO != null) {
- if (orderDTO.getOrderType().equals(IfConstant.NO)) {
- SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field(configVO.getEsField()).order(SortOrder.Asc).missing(-1)));
- optionsList.add(sortOptions);
- } else {
- SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field(configVO.getEsField()).order(SortOrder.Desc).missing(-1)));
- optionsList.add(sortOptions);
- }
- }
- }
- } else {
- SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field("patent_no.keyword").order(SortOrder.Desc).missing(-1)));
- optionsList.add(sortOptions);
- }
- builder.sort(optionsList);
- //分页
- if (current != null && size != null && current > 0 && size > 0) {
- builder.from((current.intValue() - 1) * size.intValue()).size(size.intValue());
- } else {
- builder.from(0).size(99999);
- }
- //解除最大条数限制
- builder.trackTotalHits(i -> i.enabled(true));
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<PatentColumnDTO> list = new ArrayList<>();
- long total = 0L;
- if (StringUtils.isNotEmpty(esField)) {
- Aggregate statsAgg = response.aggregations().get("statsBucket");
- total = statsAgg.statsBucket().count();
- Aggregate agg = response.aggregations().get("Agg");
- List<StringTermsBucket> termsBuckets = agg.sterms().buckets().array();
- for (StringTermsBucket termsBucket : termsBuckets) {
- String key = termsBucket.key().stringValue();
- PatentColumnDTO columnDTO = this.getPatentColumnDTO(key, projectId, esField);
- list.add(columnDTO);
- }
- } else {
- List<Hit<Patent>> hits = response.hits().hits();
- total = response.hits().total().value();
- for (Hit<Patent> hit : hits) {
- String id = hit.id();
- Patent esMess = hit.source();
- PatentColumnDTO columnDTO = this.getPatentColumnDTO(esMess, projectId, id);
- list.add(columnDTO);
- }
- }
- this.loadCoulumnDTO(list);
- dto.setTotal(total);
- dto.setPatents(list);
- dto.setPageNum(current);
- dto.setPageSize(size);
- return dto;
- }
- //封装专利清单的同族分组
- public PatentColumnDTO getPatentColumnDTO(String key, Integer projectId, String field) throws Exception {
- PatentColumnDTO dto = new PatentColumnDTO();
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- Query query = QueryBuilders.term(i -> i.field(field).value(key));
- builder.query(query);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<Hit<Patent>> hits = response.hits().hits();
- if (!CollectionUtils.isEmpty(hits)) {
- String id = hits.get(0).id();
- Patent patent = hits.get(0).source();
- dto = this.getPatentColumnDTO(patent, projectId, id);
- }
- return dto;
- }
- //装载专利清单列表的数据
- public PatentColumnDTO getPatentColumnDTO(Patent patent, Integer projectId, String id) {
- PatentColumnDTO columnDTO = new PatentColumnDTO();
- BeanUtils.copyProperties(patent, columnDTO);
- if (projectId != null) {
- try {
- columnDTO.setMergeApplicant(esPatentService.getMergeApp(projectId, id));
- } catch (IOException e) {
- columnDTO.setMergeApplicant(new ArrayList<>());
- }
- try {
- columnDTO.setMergeRightHolder(esPatentService.getMergeRight(projectId, id));
- } catch (IOException e) {
- columnDTO.setMergeRightHolder(new ArrayList<>());
- }
- try {
- columnDTO.setMergeInventor(esPatentService.getMergeInventor(projectId, id));
- } catch (IOException e) {
- columnDTO.setMergeInventor(new ArrayList<>());
- }
- }
- if (ObjectUtils.isNotEmpty(patent.getApplicantAddr())) {
- PersonAddress applicantAddr = patent.getApplicantAddr();
- columnDTO.setAppAddress(applicantAddr.getAddress());
- columnDTO.setApplicantCountry(applicantAddr.getCountry());
- columnDTO.setAppProvince(applicantAddr.getProvince());
- columnDTO.setAppCity(applicantAddr.getCity());
- columnDTO.setAppDistrict(applicantAddr.getDistrict());
- }
- if (ObjectUtils.isNotEmpty(patent.getRightHolderAddr())) {
- PersonAddress rightAddr = patent.getRightHolderAddr();
- columnDTO.setRightAddress(rightAddr.getAddress());
- columnDTO.setRightCountry(rightAddr.getCountry());
- columnDTO.setRightProvince(rightAddr.getProvince());
- columnDTO.setRightCity(rightAddr.getCity());
- columnDTO.setRightDistrict(rightAddr.getDistrict());
- }
- if (!CollectionUtils.isEmpty(patent.getPriorities())) {
- List<Priorities> priorities = patent.getPriorities();
- List<String> priorityCountrys = priorities.stream().map(Priorities::getPriorityCountry).distinct().collect(Collectors.toList());
- String priorityCountry = String.join("<br>", priorityCountrys);
- columnDTO.setPriorityCountry(priorityCountry);
- List<String> priorityNos = priorities.stream().map(Priorities::getPriorityNo).distinct().collect(Collectors.toList());
- String priorityNo = String.join("<br>", priorityNos);
- columnDTO.setPriorityNo(priorityNo);
- List<String> priorityDates = priorities.stream().map(Priorities::getPriorityDate).distinct().collect(Collectors.toList());
- String priorityDate = String.join("<br>", priorityDates);
- columnDTO.setPriorityDate(priorityDate);
- }
- columnDTO.setApplicant(esPatentService.loadName(patent.getApplicant()));
- columnDTO.setRightHolder(esPatentService.loadName(patent.getRightHolder()));
- columnDTO.setInventor(esPatentService.loadName(patent.getInventor()));
- return columnDTO;
- }
- //拼接专题库id或其他id条件
- public String appendIdsCondition(String searchCondition, Integer taskId, String productFrom, Integer projectId, Integer productId) {
- String condition = "";
- if (taskId != null) {
- if (searchCondition != null && !"".equals(searchCondition.trim())) {
- searchCondition = "taskId = " + taskId + " AND " + searchCondition;
- } else {
- searchCondition = "taskId = " + taskId;
- }
- } else {
- if (StringUtils.isNotEmpty(productFrom)) {
- if (productId != null) {
- if (searchCondition != null && !"".equals(searchCondition.trim())) {
- searchCondition = "productId = " + productId + " AND " + searchCondition;
- } else {
- searchCondition = "productId = " + productId;
- }
- }
- } else {
- if (projectId != null) {
- if (searchCondition != null && !"".equals(searchCondition.trim())) {
- searchCondition = "projectId = " + projectId + " AND " + searchCondition;
- } else {
- searchCondition = "projectId = " + projectId;
- }
- }
- }
- }
- condition = searchCondition;
- return condition;
- }
- /**
- * 解析自定义栏位和值
- *
- * @param customFields
- * @return
- */
- public String parseCustomField(List<EsCustomFieldValueDTO> customFields, Integer projectId, Integer taskId) throws Exception {
- int m = 1;
- int n = 0;
- StringBuilder builder = new StringBuilder();
- long start = System.currentTimeMillis();
- if (customFields.size() > m) {
- for (int i = 0; i < customFields.size(); i++) {
- EsCustomFieldValueDTO customField = customFields.get(i);
- if (i != n) {
- builder.append(" ").append("and").append(" ").append("(");
- this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
- } else {
- builder.append("(");
- this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
- }
- }
- } else {
- for (int i = 0; i < customFields.size(); i++) {
- EsCustomFieldValueDTO customField = customFields.get(i);
- if (i != n) {
- builder.append(" ").append("and").append(" ");
- this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
- } else {
- builder.append("(");
- this.appendStr(customField, builder, m, customField.getIfHaveChild(), projectId, taskId);
- }
- }
- }
- long end = System.currentTimeMillis();
- System.out.println("耗时" + (end - start));
- return builder.toString();
- }
- public void appendStr(EsCustomFieldValueDTO customField, StringBuilder builder, int m, boolean ifHaveChild,
- Integer projectId, Integer taskId) throws Exception {
- builder.append("field").append("=").append(customField.getFieldId());
- List<String> values = customField.getFieldValue();
- if (values.contains("未选择")) {
- values.removeIf(value -> value.equals("未选择"));
- values.add("未选择");
- }
- if (!CollectionUtils.isEmpty(values)) {
- builder.append(" ").append("and").append(" ");
- if (ifHaveChild) {
- builder.append("statsValue").append("=");
- } else {
- builder.append("fieldValue").append("=");
- }
- if (values.size() > m) {
- builder.append("(");
- for (int j = 0; j < values.size(); j++) {
- String s = values.get(j);
- if (j != values.size() - m) {
- builder.append(s).append(" ").append("or").append(" ");
- } else {
- if (s.equals("未选择")) {
- GetUnselectedDTO unselectedDTO = esCountService.getUnselectedCustomNum(projectId, customField.getFieldId());
- List<String> childIds = unselectedDTO.getBeinglessChildIds();
- String noCondition = this.appendIds(childIds);
- builder.append(s).append(")").append(" ").append("OR")
- .append(" ").append("(").append(noCondition).append(")").append(")");
- } else {
- builder.append(s).append(")").append(")");
- }
- }
- }
- } else {
- for (String value : values) {
- if (value.equals("未选择")) {
- GetUnselectedDTO unselectedDTO = esCountService.getUnselectedCustomNum(projectId, customField.getFieldId());
- List<String> childIds = unselectedDTO.getBeinglessChildIds();
- String noCondition = this.appendIds(childIds);
- builder.append(value).append(" ").append("OR").append(" ").append(noCondition).append(")");
- } else {
- builder.append(value).append(")");
- }
- }
- }
- } else {
- builder.append(")");
- }
- }
- //拼接ids
- public String appendIds(List<String> nos) {
- String str = "ids = ";
- if (nos.size() > 1) {
- str = str + "\"";
- for (int i = 0; i < nos.size(); i++) {
- String s = nos.get(i);
- if (i != nos.size() - 1) {
- str = str + s + ",";
- } else {
- str = str + s + "\"";
- }
- }
- } else {
- for (String no : nos) {
- str = str + no;
- }
- }
- return str;
- }
- //更新patent
- public Integer updatePatent(Patent patent, String id) {
- UpdateRequest<Patent, Patent> req;
- req = UpdateRequest.of(
- b -> b.index("patent").id(id)
- .doc(patent)
- );
- try {
- client.update(req, Patent.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- //更新patent
- public Integer updatePatentShouldWait(Patent patent, String id) {
- UpdateRequest<Patent, Patent> req;
- req = UpdateRequest.of(
- b -> b.index("patent").id(id)
- .doc(patent).refresh(Refresh.True)
- );
- try {
- client.update(req, Patent.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- //更新patent
- public Integer updatePatentById(Patent patent, String id) {
- UpdateRequest<Patent, Patent> req;
- req = UpdateRequest.of(
- b -> b.index("patent").id(id)
- .doc(patent));
- try {
- client.update(req, Patent.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- //获取父文档相关的所有自定义子文档,按照时间按倒序,首个改为最新数据,其他if——new改为0:不是最新
- public Integer getIds(String parentId, Integer projectId, Integer taskId, String fieldId) throws Exception {
- int ifNew = 0;
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- Query q1 = QueryBuilders.hasParent(i -> i.parentType("patent").query(j -> j.ids(IdsQuery.of(k -> k.values(parentId)))));
- Query q2 = QueryBuilders.exists(i -> i.field("custom_field"));
- Query q3 = QueryBuilders.term(i -> i.field("custom_field.project_id").value(projectId));
- Query q4 = QueryBuilders.term(i -> i.field("custom_field.field").value(fieldId));
- Query bool = QueryBuilders.bool(i -> i.must(q1, q2, q3, q4));
- builder.query(bool);
- List<SortOptions> optionsList = new ArrayList<>();
- SortOptions sortOptions = SortOptions.of(i -> i.field(j -> j.field("custom_field.create_time").order(SortOrder.Desc).missing(-1)));
- optionsList.add(sortOptions);
- builder.sort(optionsList);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<Hit<Patent>> hits = response.hits().hits();
- Map<String, ESCustomField> map = new HashMap<>();
- for (Hit<Patent> hit : hits) {
- String id = hit.id();
- Patent patent = hit.source();
- map.put(id, patent.getESCustomField());
- }
- if (!CollectionUtils.isEmpty(map)) {
- for (String id : map.keySet()) {
- ESCustomField esCustomField = map.get(id);
- esCustomField.setIfNew(0);
- Patent patent = new Patent();
- patent.setESCustomField(esCustomField);
- Integer aNew = this.updateCustomFieldIfNew(patent, id);
- if (aNew > 0) {
- ifNew++;
- } else {
- ifNew = 0;
- break;
- }
- }
- }
- return ifNew;
- }
- //更新自定义文档是否是最新数据
- public Integer updateCustomFieldIfNew(Patent patent, String id) throws IOException {
- ESCustomField customField = patent.getESCustomField();
- String source = "ctx._source.custom_field.if_new = " + customField.getIfNew();
- InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").source(source));
- Script script = Script.of(i -> i.inline(inlineScript));
- Query query = QueryBuilders.term(i -> i.field("_id").value(id));
- UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).refresh(true).query(query));
- try {
- client.updateByQuery(request);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- //更新子文档
- public Integer updateByQuery(Patent patent, String id) throws Exception {
- ESCustomField customField = patent.getESCustomField();
- String parentId = patent.getPatentJoin().getParent();
- Integer num = this.getIds(parentId, customField.getProjectId(), customField.getTaskId(), customField.getField());
- if (num < 1) {
- throw new XiaoShiException("子文档是否最新更新失败");
- }
- String valueField = "[";
- List<String> fieldValueList = customField.getFieldValue();
- if (!CollectionUtils.isEmpty(fieldValueList)) {
- int lastSum = fieldValueList.size() - 1;
- for (int i = 0; i < fieldValueList.size(); i++) {
- String s = fieldValueList.get(i);
- if (i == lastSum) {
- valueField = valueField + "\"" + s + "\"";
- } else {
- valueField = valueField + "\"" + s + "\"" + ",";
- }
- }
- }
- valueField = valueField + "]";
- String valueStats = "[";
- List<String> statsValueList = customField.getStatsValue();
- if (!CollectionUtils.isEmpty(statsValueList)) {
- int lastSum = statsValueList.size() - 1;
- for (int i = 0; i < statsValueList.size(); i++) {
- String s = statsValueList.get(i);
- if (i == lastSum) {
- valueStats = valueStats + "\"" + s + "\"";
- } else {
- valueStats = valueStats + "\"" + s + "\"" + ",";
- }
- }
- }
- valueStats = valueStats + "]";
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- String s = format.format(customField.getCreateTime());
- String dateStr = "\'" + s + "\'";
- String projectId = "ctx._source.custom_field.project_id = " + customField.getProjectId() + ";";
- String taskId = "ctx._source.custom_field.task_id = " + customField.getTaskId() + ";";
- String ifNew = "ctx._source.custom_field.if_new = " + 1 + ";";
- String field = "ctx._source.custom_field.field=" + customField.getField() + ";";
- String fieldType = "ctx._source.custom_field.field_type = " + customField.getFieldType() + ";";
- String personId = "ctx._source.custom_field.person_id = " + customField.getPersonId() + ";";
- String createTime = "ctx._source.custom_field.create_time = " + dateStr + ";";
- String fieldValue = "ctx._source.custom_field.field_value = " + valueField + ";";
- String statsValue = "ctx._source.custom_field.stats_value = " + valueStats;
- String source = projectId + taskId + ifNew + field + fieldType + personId + createTime + fieldValue + statsValue;
- InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").source(source));
- Script script = Script.of(i -> i.inline(inlineScript));
- Query query = QueryBuilders.term(i -> i.field("_id").value(id));
- UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).refresh(true).query(query));
- try {
- client.updateByQuery(request);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- /**
- * @param key
- * @param page
- * @param limit
- * @return
- * @throws IOException
- */
- public List<Patent> searchChild(String key, Integer page, Integer limit) throws IOException {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- //组装查询条件
- HasChildQuery.Builder hasChildQuery = new HasChildQuery.Builder();
- hasChildQuery.type("project");
- hasChildQuery.query(q -> q.match(m -> m
- .query(key)
- //字段名
- .field("project_id")
- ));
- builder.query(q -> q.hasChild(hasChildQuery.build()));
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<Patent> list = new ArrayList<>();
- List<Hit<Patent>> hits = response.hits().hits();
- for (Hit<Patent> hit : hits) {
- Patent esMess = hit.source();
- list.add(esMess);
- }
- return list;
- }
- /**
- * 查询是否存在专利
- *
- * @param parentId
- * @param projectId
- * @return
- */
- public Boolean searchPatent(String parentId, Integer projectId) throws IOException {
- boolean flag = false;
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- Query q1 = QueryBuilders.term(t -> t.field("project_id").value(projectId));
- Query q2 = QueryBuilders.parentId(parent -> parent.type("project").id(parentId));
- Query bool = QueryBuilders.bool(i -> i.must(q1, q2));
- builder.query(bool);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- long total = response.hits().total().value();
- if (total > 0) {
- flag = true;
- }
- return flag;
- }
- /**
- * 查询是否存在专利
- *
- * @param parentId
- * @param projectId
- * @return
- */
- public Boolean ifInTask(String parentId, Integer projectId, Integer taskId) throws IOException {
- boolean flag = false;
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- Query q1 = QueryBuilders.term(t -> t.field("import_task.project_id").value(projectId));
- Query q3 = QueryBuilders.term(t -> t.field("import_task.task_id").value(projectId));
- Query q2 = QueryBuilders.parentId(parent -> parent.type("import_task").id(parentId));
- Query bool = QueryBuilders.bool(i -> i.must(q1, q2, q3));
- builder.query(bool);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- long total = response.hits().total().value();
- if (total > 0) {
- flag = true;
- }
- return flag;
- }
- /**
- * 查询同族
- *
- * @param nos
- * @param type
- * @return
- * @throws IOException
- */
- public EsPatentFamilyDTO addEsPatentFamily(Patent patent, List<String> nos, String type) throws Exception {
- EsPatentFamilyDTO esDTO = new EsPatentFamilyDTO();
- List<String> absentList = new ArrayList<>();
- PatentFamilyMessage patentFamilyMessage = null;
- String id = "";
- PatentFamilyMessageWithId patentFamilyMessageWithId = queryPatentFamily(patent, type);
- if (patentFamilyMessageWithId != null) {
- patentFamilyMessage = patentFamilyMessageWithId.getPatentFamilyMessage();
- id = patentFamilyMessageWithId.getId();
- } else {
- //遍历,根据专利号查询同族
- for (String no : nos) {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent_family");
- //申请号
- Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(no));
- //公开号
- Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(no));
- //授权号
- Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(no));
- //类型
- Query q4 = QueryBuilders.term(t -> t.field("family_type").value(type));
- Query p = QueryBuilders.bool(i -> i.should(q1, q2, q3));
- Query bool = QueryBuilders.bool(i -> i.must(q4, p));
- builder.query(bool);
- SearchResponse<PatentFamilyMessage> response = client.search(builder.build(), PatentFamilyMessage.class);
- long total = response.hits().total().value();
- if (total > 0) {
- List<FamilyPatent> list = new ArrayList<>();
- List<Hit<PatentFamilyMessage>> hits = response.hits().hits();
- Hit<PatentFamilyMessage> hit = hits.get(0);
- id = hit.id();
- patentFamilyMessage = hit.source();
- break;
- }
- }
- }
- List<String> notInNos = new ArrayList<>();
- //当查询到同族时
- if (patentFamilyMessage != null) {
- List<FamilyPatent> familyPatents = patentFamilyMessage.getPatent();
- for (String no : nos) {
- FamilyPatent familyPatent = familyPatents.stream()
- .filter(item -> item.getAppNo() != null && item.getAppNo().equals(no) ||
- item.getPublicNo() != null && item.getPublicNo().equals(no) ||
- item.getGrantNo() != null && item.getGrantNo().equals(no))
- .findFirst().orElse(null);
- if (familyPatent == null) {
- notInNos.add(no);
- }
- }
- }
- //当未查询到同族时
- else {
- patentFamilyMessage = new PatentFamilyMessage();
- patentFamilyMessage.setFamilyType(type);
- patentFamilyMessage.setPatent(new ArrayList<>());
- notInNos.addAll(nos);
- }
- List<FamilyPatent> familyPatents = patentFamilyMessage.getPatent();
- String appNo = "";
- String publicNo = "";
- String grantNo = "";
- if (patent.getAppNo() != null) {
- appNo = patent.getAppNo();
- }
- if (patent.getPublicNo() != null) {
- publicNo = patent.getPublicNo();
- }
- if (patent.getGrantNo() != null) {
- grantNo = patent.getGrantNo();
- }
- String appNo1 = appNo;
- String publicNo1 = publicNo;
- String grantNo1 = grantNo;
- FamilyPatent patent1 = familyPatents.stream().filter(item ->
- publicNo1.equals(item.getPublicNo())
- || publicNo1.equals(item.getGrantNo())
- || grantNo1.equals(item.getPublicNo())
- || grantNo1.equals(item.getGrantNo())
- ).findFirst().orElse(null);
- if (patent1 == null) {
- patent1 = new FamilyPatent();
- patent1.setGrantNo(patent.getGrantNo());
- patent1.setAppNo(patent.getAppNo());
- patent1.setPublicNo(patent.getPublicNo());
- familyPatents.add(patent1);
- } else {
- patent1.setGrantNo(patent.getGrantNo());
- patent1.setAppNo(patent.getAppNo());
- patent1.setPublicNo(patent.getPublicNo());
- }
- if (notInNos.size() > 0) {
- //所有专利号的专利详情
- List<FamilyPatent> patents = new ArrayList<>();
- notInNos.forEach(item -> {
- FamilyPatent familyPatent = new FamilyPatent();
- familyPatent.setPublicNo(item);
- patents.add(familyPatent);
- });
- patentFamilyMessage.getPatent().addAll(patents);
- }
- //当id不为null时
- if (!id.equals("")) {
- this.updatePatentFamily(patentFamilyMessage, id);
- } else {
- try {
- id = this.addPatentFamily(patentFamilyMessage);
- } catch (Exception e) {
- }
- }
- esDTO.setPatentFamilyId(id);
- esDTO.setFamilyNum(patentFamilyMessage.getPatent().size());
- return esDTO;
- }
- /**
- * 添加同族
- *
- * @param message
- * @return
- * @throws Exception
- */
- public String addPatentFamily(PatentFamilyMessage message) throws Exception {
- IndexResponse indexResponse = client.index(i -> i
- .index("patent_family")
- .document(message)
- );
- return indexResponse.id();
- }
- /**
- * 更新同族
- *
- * @param message
- * @param id
- * @return
- */
- public Integer updatePatentFamily(PatentFamilyMessage message, String id) {
- UpdateRequest<PatentFamilyMessage, PatentFamilyMessage> req;
- req = UpdateRequest.of(
- b -> b.index("patent_family")
- .id(id)
- .doc(message)
- );
- try {
- client.update(req, PatentFamilyMessage.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- /**
- * 更新专利事务
- *
- * @param
- * @param id
- * @return
- */
- public Integer updateLegalEvent(LegalEvent legalEvent, String id) {
- UpdateRequest<LegalEvent, LegalEvent> req;
- req = UpdateRequest.of(
- b -> b.index("legal_event")
- .id(id)
- .doc(legalEvent).refresh(Refresh.True).waitForActiveShards(WaitForActiveShards.of(i -> i.count(1)))
- );
- try {
- client.update(req, LegalEvent.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- /**
- * 添加法律事务
- *
- * @param
- * @return
- * @throws Exception
- */
- public String addLegalEvent(LegalEvent legalEvent) throws Exception {
- IndexResponse indexResponse = client.index(i -> i
- .index("legal_event")
- .document(legalEvent).refresh(Refresh.True).waitForActiveShards(WaitForActiveShards.of(t -> t.count(1)))
- );
- return indexResponse.id();
- }
- /**
- * 更新专利事务
- *
- * @param
- * @param id
- * @return
- */
- public Integer updateQuotePatent(PatentQuoteMessage patentQuoteMessage, String id) {
- UpdateRequest<PatentQuoteMessage, PatentQuoteMessage> req;
- req = UpdateRequest.of(
- b -> b.index("quote_patent")
- .id(id)
- .doc(patentQuoteMessage)
- );
- try {
- client.update(req, PatentQuoteMessage.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- /**
- * 添加法律事务
- *
- * @param
- * @return
- * @throws Exception
- */
- public String addQuotePatent(PatentQuoteMessage patentQuoteMessage) throws Exception {
- IndexResponse indexResponse = client.index(i -> i
- .index("quote_patent")
- .document(patentQuoteMessage)
- );
- return indexResponse.id();
- }
- public String addEsQuotePatent(StarPatentVO starPatentVO, List<String> nos) throws Exception {
- if (starPatentVO == null) {
- return null;
- }
- QuotePatent quotePatent = this.reQuotePatent(starPatentVO);
- PatentQuoteMessage patentQuoteMessage = null;
- //根据申请号和
- String id = "";
- //根据专利号查询是否有引用信息
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("quote_patent");
- //申请号
- Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(starPatentVO.getApplicationNo()));
- Query bool = QueryBuilders.bool(i -> i.must(q1));
- builder.query(bool);
- SearchResponse<PatentQuoteMessage> response = client.search(builder.build(), PatentQuoteMessage.class);
- long total = response.hits().total().value();
- if (total > 0) {
- patentQuoteMessage = response.hits().hits().get(0).source();
- id = response.hits().hits().get(0).id();
- }
- List<QuotePatent> quotePatents = new ArrayList<>();
- if (patentQuoteMessage != null && patentQuoteMessage.getQuotedPatents() != null) {
- quotePatents = patentQuoteMessage.getQuotedPatents();
- }
- if (nos != null && nos.size() > 0) {
- List<Patent> patents = esPatentService.getPatentsByNo(nos, true, null, null);
- for (String patentNo : nos) {
- QuotePatent quotePatent1 = null;
- if (quotePatents.size() > 0) {
- quotePatent1 = quotePatents.stream()
- .filter(item -> patentNo.equals(item.getAppNo()) || patentNo.equals(item.getPublicNo()) || patentNo.equals(item.getGrantNo())).findFirst().orElse(null);
- }
- Patent patent = patents.stream().filter(item -> patentNo.equals(item.getAppNo())).findFirst().orElse(null);
- if (quotePatent1 == null) {
- quotePatent1 = this.reQuotePatent(patent, patentNo);
- quotePatents.add(quotePatent1);
- } else {
- quotePatent1 = this.reQuotePatent(patent, patentNo);
- }
- }
- }
- if (patentQuoteMessage == null) {
- if (quotePatents.size() != 0) {
- patentQuoteMessage = new PatentQuoteMessage();
- patentQuoteMessage.setPatent(quotePatent);
- patentQuoteMessage.setQuotedPatents(quotePatents);
- this.addQuotePatent(patentQuoteMessage);
- }
- } else {
- patentQuoteMessage.getQuotedPatents().addAll(quotePatents);
- this.updateQuotePatent(patentQuoteMessage, id);
- }
- return "";
- }
- private QuotePatent reQuotePatent(StarPatentVO starPatentVO) {
- QuotePatent quotePatent = new QuotePatent();
- //装载申请人
- if (starPatentVO.getApplicantStr() != null && !starPatentVO.getApplicantStr().equals("")) {
- List<String> names = Arrays.asList(starPatentVO.getApplicantStr().split(";"));
- List<PatentPerson> patentPeople = new ArrayList<>();
- for (int i = 0; i < names.size(); i++) {
- PatentPerson patentPerson = new PatentPerson();
- patentPerson.setOrder(i + 1);
- patentPerson.setType("1");
- patentPerson.setName(names.get(i));
- patentPeople.add(patentPerson);
- }
- quotePatent.setApplicant(patentPeople);
- }
- //装载权利人
- if (starPatentVO.getCurrentApplicantStr() != null && !starPatentVO.getCurrentApplicantStr().equals("")) {
- List<String> names = Arrays.asList(starPatentVO.getCurrentApplicantStr().split(";"));
- List<PatentPerson> patentPeople = new ArrayList<>();
- for (int i = 0; i < names.size(); i++) {
- PatentPerson patentPerson = new PatentPerson();
- patentPerson.setOrder(0);
- patentPerson.setType("1");
- patentPerson.setName(names.get(i));
- patentPeople.add(patentPerson);
- }
- quotePatent.setRightHolder(patentPeople);
- }
- quotePatent.setAppNo(starPatentVO.getApplicationNo());
- quotePatent.setGrantNo(starPatentVO.getPublicAccreditNo());
- quotePatent.setPublicNo(starPatentVO.getPublicNo());
- return quotePatent;
- }
- private QuotePatent reQuotePatent(Patent patent, String no) {
- QuotePatent quotePatent = new QuotePatent();
- if (patent == null) {
- quotePatent.setPublicNo(no);
- return quotePatent;
- }
- //装载申请人
- quotePatent.setApplicant(patent.getApplicant());
- quotePatent.setRightHolder(patent.getRightHolder());
- quotePatent.setAppNo(patent.getAppNo());
- quotePatent.setGrantNo(patent.getGrantNo());
- quotePatent.setPublicNo(patent.getPublicNo());
- return quotePatent;
- }
- public String addEsLegalEvent(StarPatentVO starPatentVO) {
- LegalEvent legalEvent = null;
- String id = "";
- //根据专利号查询
- if (starPatentVO == null) {
- return null;
- }
- String cnLegalApiStr = patentStarApiService.getCnLegalApi(starPatentVO.getRowApplicationNo());
- if (cnLegalApiStr != null && !cnLegalApiStr.equals("")) {
- List<LegalEvent> legalEvents = new ArrayList<>();
- //根据专利号查询是否有引用信息
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("legal_event");
- //申请号
- List<Query> queries = new ArrayList<>();
- if (starPatentVO.getApplicationNo() != null) {
- Query q1 = QueryBuilders.term(t -> t.field("app_no").value(starPatentVO.getApplicationNo()));
- queries.add(q1);
- }
- if (starPatentVO.getPublicAccreditNo() != null) {
- Query q2 = QueryBuilders.term((t -> t.field("grant_no").value(starPatentVO.getPublicAccreditNo())));
- queries.add(q2);
- }
- if (starPatentVO.getPublicNo() != null) {
- Query q3 = QueryBuilders.term((t -> t.field("public_no").value(starPatentVO.getPublicNo())));
- queries.add(q3);
- }
- Query bool = QueryBuilders.bool(i -> i.should(queries));
- builder.query(bool);
- SearchResponse<LegalEvent> response = null;
- try {
- response = client.search(builder.build(), LegalEvent.class);
- } catch (IOException e) {
- e.printStackTrace();
- }
- long total = response.hits().total().value();
- if (total > 0) {
- response.hits().hits().forEach(item -> {
- legalEvents.add(item.source());
- });
- }
- if (!cnLegalApiStr.contains("408")) {
- List<ChinaLeagalStatus> chinaLeagalStatuses = JSON.parseArray(cnLegalApiStr, ChinaLeagalStatus.class);
- chinaLeagalStatuses.forEach(item -> {
- LegalEvent tem = legalEvents.stream().filter(em -> em.getEventDate() != null && em.getEventDate().compareTo(item.getLegalDate()) == 0).findFirst().orElse(null);
- if (tem == null) {
- LegalEvent legalEvent1 = new LegalEvent();
- legalEvent1.setEventDate(item.getLegalDate());
- legalEvent1.setCode(item.getLegalCode());
- legalEvent1.setAppNo(starPatentVO.getApplicationNo());
- legalEvent1.setGrantNo(starPatentVO.getPublicAccreditNo());
- legalEvent1.setPublicNo(starPatentVO.getPublicNo());
- legalEvent1.setDescription(item.getLegalStatusInfo());
- legalEvent1.setName(item.getLegalStatus());
- try {
- String reId = this.addLegalEvent(legalEvent1);
- } catch (Exception e) {
- throw new XiaoShiException(e.getMessage());
- }
- }
- });
- }
- }
- return "";
- }
- /**
- * 查询权利要求
- *
- * @param patentNo
- * @return
- */
- public SelectClaimDTO selectClaim(String patentNo) throws IOException {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- //原始数据
- Query q = QueryBuilders.term(t -> t.field("claim.if_origin").value(true));
- //申请号
- Query q1 = QueryBuilders.term(t -> t.field("app_no.keyword").value(patentNo));
- //公开号
- Query q2 = QueryBuilders.term(t -> t.field("public_no.keyword").value(patentNo));
- //授权号
- Query q3 = QueryBuilders.term(t -> t.field("grant_no.keyword").value(patentNo));
- Query query = QueryBuilders.bool(i -> i.should(q1, q2, q3));
- Query bool = QueryBuilders.bool(i -> i.must(q, query));
- builder.query(bool);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- SelectClaimDTO dto = new SelectClaimDTO();
- List<Hit<Patent>> hits = response.hits().hits();
- for (Hit<Patent> hit : hits) {
- Patent esMess = hit.source();
- if (esMess != null) {
- dto.setClaimContent(esMess.getClaim());
- dto.setClaim(esMess.getClaim().get(0).getTextContent());
- }
- }
- return dto;
- }
- /**
- * 装载摘要附图
- *
- * @param patentColumnDTOS
- * @return
- */
- public List<PatentColumnDTO> loadCoulumnDTO(List<PatentColumnDTO> patentColumnDTOS) {
- patentColumnDTOS.forEach(item -> {
- item.setPictureGuid(FormatUtil.getPictureFormat(item.getAppNo()));
- });
- return patentColumnDTOS;
- }
- /**
- * 根据专利号查询出其他专利号
- *
- * @param patentNos
- * @return
- * @throws IOException
- */
- public SelectClaimDTO selectPatentNo(List<String> patentNos) throws IOException {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- List<Query> queryList = new ArrayList<>();
- for (String patentNo : patentNos) {
- Query q1 = QueryBuilders.term(t -> t.field("patent_no.keyword").value(patentNo));
- queryList.add(q1);
- }
- //申请号
- Query query = QueryBuilders.bool(i -> i.mustNot(queryList));
- builder.query(query);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- SelectClaimDTO dto = new SelectClaimDTO();
- List<Hit<Patent>> hits = response.hits().hits();
- long value = response.hits().total().value();
- if (value > 1) {
- System.out.println("====================" + value);
- }
- return dto;
- }
- /**
- * 更新合并申请人/权利人/发明人
- *
- * @param patent
- * @param id
- * @return
- */
- public Integer updateMergePerson(Patent patent, String id) {
- UpdateRequest<Patent, Patent> req;
- req = UpdateRequest.of(
- b -> b.index("patent")
- .id(id)
- .doc(patent)
- .docAsUpsert(true)
- );
- try {
- client.update(req, Patent.class);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- /**
- * 删除申请人/权利人/发明人合并名称
- *
- * @param patent
- * @param id
- * @return
- */
- public Integer delMergePerson(Patent patent, String id, Integer type, String name) {
- String source = "";
- if (type == 0) {
- 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); }";
- } else {
- source = "if (ctx._source.merge_inventor != null) { ctx._source.merge_inventor.removeIf(item -> item.name == params.name); }";
- }
- String finalSource = source;
- InlineScript inlineScript = InlineScript.of(i -> i.lang("painless").params("name", JsonData.of(name)).source(finalSource));
- Script script = Script.of(i -> i.inline(inlineScript));
- Query query = QueryBuilders.term(i -> i.field("_id").value(id));
- UpdateByQueryRequest request = UpdateByQueryRequest.of(i -> i.index("patent").script(script).query(query));
- try {
- client.updateByQuery(request);
- return 1;
- } catch (IOException e) {
- return -1;
- }
- }
- public PatentFamilyMessageWithId queryPatentFamily(Patent patent, String type) throws Exception {
- //查询该专利是否已有同族
- SearchRequest.Builder builderPatent = new SearchRequest.Builder();
- //设置查询索引
- builderPatent.index("patent_family");
- //申请号
- List<Query> queries = new ArrayList<>();
- if (patent.getAppNo() != null) {
- Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getAppNo()));
- //公开号
- Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(patent.getAppNo()));
- //授权号
- Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(patent.getAppNo()));
- //类型
- queries.add(q1);
- queries.add(q2);
- queries.add(q3);
- }
- if (patent.getPublicNo() != null) {
- Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getPublicNo()));
- //公开号
- Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(patent.getPublicNo()));
- //授权号
- Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(patent.getPublicNo()));
- queries.add(q1);
- queries.add(q2);
- queries.add(q3);
- }
- if (patent.getGrantNo() != null) {
- Query q1 = QueryBuilders.term(t -> t.field("patent.app_no").value(patent.getGrantNo()));
- //公开号
- Query q2 = QueryBuilders.term(t -> t.field("patent.public_no").value(patent.getGrantNo()));
- //授权号
- Query q3 = QueryBuilders.term(t -> t.field("patent.grant_no").value(patent.getGrantNo()));
- queries.add(q1);
- queries.add(q2);
- queries.add(q3);
- }
- Query q4 = QueryBuilders.term(t -> t.field("family_type").value(type));
- Query p = QueryBuilders.bool(i -> i.should(queries));
- Query bool = QueryBuilders.bool(i -> i.must(q4, p));
- builderPatent.query(bool);
- SearchResponse<PatentFamilyMessage> response = client.search(builderPatent.build(), PatentFamilyMessage.class);
- long total = response.hits().total().value();
- if (total > 0) {
- List<FamilyPatent> list = new ArrayList<>();
- List<Hit<PatentFamilyMessage>> hits = response.hits().hits();
- Hit<PatentFamilyMessage> hit = hits.get(0);
- String id = hit.id();
- PatentFamilyMessageWithId patentFamilyMessageWithId = new PatentFamilyMessageWithId();
- patentFamilyMessageWithId.setId(id);
- patentFamilyMessageWithId.setPatentFamilyMessage(hit.source());
- return patentFamilyMessageWithId;
- }
- return null;
- }
- //根据父id获取相应专利的专利号
- public List<String> getPatentNos(List<String> ids) throws IOException {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- Query q = QueryBuilders.ids(i -> i.values(ids));
- builder.size(9999);
- builder.query(q);
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<Hit<Patent>> hits = response.hits().hits();
- List<String> list = new ArrayList<>();
- for (Hit<Patent> hit : hits) {
- Patent patent = hit.source();
- list.add(patent.getPatentNo());
- }
- return list;
- }
- @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
- public Boolean deletePatents(EsCustomFieldBatchVO vo) throws Exception {
- Integer projectId = vo.getProjectId();
- Integer startNum = vo.getStartNumber();
- Integer endNum = vo.getEndNumber();
- List<String> isAdd = vo.getIsAdd();
- List<String> isDel = vo.getIsDelete();
- if (!CollectionUtils.isEmpty(isAdd) && startNum <= 1 && endNum < 1) {
- isAdd.removeAll(isDel);
- for (String patentNo : isAdd) {
- Integer number = this.getPatent(patentNo, projectId);
- if (number < 1) {
- throw new XiaoShiException("删除失败");
- }
- }
- } else if (startNum >= 1 && endNum > 0) {
- List<String> patentNos = esCustomFieldService.getPatentNos(vo);
- for (String patentNo : patentNos) {
- Integer number = this.getPatent(patentNo, projectId);
- if (number < 1) {
- throw new XiaoShiException("删除失败");
- }
- }
- }
- return true;
- }
- public Integer getPatent(String patentNo, Integer projectId) throws IOException {
- SearchRequest.Builder builder = new SearchRequest.Builder();
- //设置查询索引
- builder.index("patent");
- Query query = QueryBuilders.term(i -> i.field("project_id").value(projectId));
- Query q = QueryBuilders.term(i -> i.field("patent_no.keyword").value(patentNo));
- Query query1 = QueryBuilders.hasParent(i -> i.parentType("patent").query(q));
- Query bool = QueryBuilders.bool(i -> i.must(query, query1));
- builder.query(bool);
- //解除最大条数限制
- builder.trackTotalHits(i -> i.enabled(true));
- SearchResponse<Patent> response = client.search(builder.build(), Patent.class);
- List<Hit<Patent>> hits = response.hits().hits();
- List<String> list = new ArrayList<>();
- for (Hit<Patent> hit : hits) {
- String id = hit.id();
- list.add(id);
- }
- return this.deleteByIds(list);
- }
- public Integer deleteByIds(List<String> ids) {
- Query query = QueryBuilders.ids(n -> n.values(ids));
- DeleteByQueryRequest request = DeleteByQueryRequest.of(i -> i.index("patent").query(query)
- .refresh(true));
- try {
- client.deleteByQuery(request);
- return 1;
- } catch (IOException e) {
- throw new XiaoShiException("删除失败");
- }
- }
- }
|