Search in sources :

Example 1 with KmSearchResultObjVO

use of org.jeecg.common.system.vo.KmSearchResultObjVO in project kms by mahonelau.

the class KmDocController method docDPCheck.

// 以下是ES库综合检索api
/**
 * @param docId     指想排重的docid
 * @param checkType
 * @功能描述 传入指定的indexid,列出相似的文档
 */
@ApiOperation(value = "km_doc-排重检索", notes = "km_doc-排重检索")
@GetMapping(value = "/docDPCheck")
public Result<?> docDPCheck(String docId, String checkType, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
    try {
        KmDocEsParamVO kmDocEsParamVO = new KmDocEsParamVO();
        kmDocEsParamVO.setColumn("_score");
        kmDocEsParamVO.setOrder("desc");
        KmDoc kmDoc = kmDocService.getById(docId);
        if (kmDoc != null) {
            String docTitle = kmDoc.getTitle();
            if (checkType.equals("1") && docTitle != null && !docTitle.isEmpty())
                kmDocEsParamVO.setTitle(docTitle);
            Page<KmSearchResultVO> page = new Page<KmSearchResultVO>(pageNo, pageSize);
            KmSearchResultObjVO kmSearchResultObjVO = kmDocService.checkDuplicateESKmDoc(page, kmDocEsParamVO, req);
            if (kmSearchResultObjVO.isSuccess()) {
                dictUtils.parseDictText(kmSearchResultObjVO);
                return Result.OK(kmSearchResultObjVO);
            } else
                return Result.error(kmSearchResultObjVO.getMessage());
        } else {
            return Result.error("doc not found");
        }
    } catch (IOException e) {
        return Result.error(e.getMessage());
    }
}
Also used : KmDoc(org.jeecg.modules.KM.entity.KmDoc) KmSearchResultObjVO(org.jeecg.common.system.vo.KmSearchResultObjVO) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) IPage(com.baomidou.mybatisplus.core.metadata.IPage) ApiOperation(io.swagger.annotations.ApiOperation)

Example 2 with KmSearchResultObjVO

use of org.jeecg.common.system.vo.KmSearchResultObjVO in project kms by mahonelau.

the class DictAspect method parseDictText.

/**
 * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
 * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
 * 示例为SysUser   字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
 * 例输入当前返回值的就会多出一个sex_dictText字段
 * {
 *      sex:1,
 *      sex_dictText:"男"
 * }
 * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
 *  customRender:function (text) {
 *               if(text==1){
 *                 return "男";
 *               }else if(text==2){
 *                 return "女";
 *               }else{
 *                 return text;
 *               }
 *             }
 *             目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
 * @param result
 */
private void parseDictText(Object result) {
    if (result instanceof Result) {
        if (((Result) result).getResult() instanceof IPage) {
            List<JSONObject> items = new ArrayList<>();
            for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    // 解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                JSONObject item = JSONObject.parseObject(json);
                // for (Field field : record.getClass().getDeclaredFields()) {
                for (Field field : oConvertUtils.getAllFields(record)) {
                    // update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    if (field.getAnnotation(Dict.class) != null) {
                        String code = field.getAnnotation(Dict.class).dicCode();
                        String text = field.getAnnotation(Dict.class).dicText();
                        String table = field.getAnnotation(Dict.class).dictTable();
                        String key = String.valueOf(item.get(field.getName()));
                        // 翻译字典值对应的txt
                        String textValue = translateDictValue(code, text, table, key);
                        log.debug(" 字典Val : " + textValue);
                        log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                        item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                    }
                    // date类型默认转换string格式化日期
                    if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                        SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                    }
                }
                items.add(item);
            }
            ((IPage) ((Result) result).getResult()).setRecords(items);
        } else if (((Result) result).getResult() instanceof KmSearchResultObjVO) {
            List<JSONObject> items = new ArrayList<>();
            for (Object record : ((KmSearchResultObjVO) ((Result) result).getResult()).getKmSearchResultVOPage().getRecords()) {
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    // 解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                JSONObject item = JSONObject.parseObject(json);
                // for (Field field : record.getClass().getDeclaredFields()) {
                for (Field field : oConvertUtils.getAllFields(record)) {
                    // update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    if (field.getAnnotation(Dict.class) != null) {
                        String code = field.getAnnotation(Dict.class).dicCode();
                        String text = field.getAnnotation(Dict.class).dicText();
                        String table = field.getAnnotation(Dict.class).dictTable();
                        String key = String.valueOf(item.get(field.getName()));
                        // 翻译字典值对应的txt
                        String textValue = translateDictValue(code, text, table, key);
                        log.debug(" 字典Val : " + textValue);
                        log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                        item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                    }
                    // date类型默认转换string格式化日期
                    if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                        SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                    }
                }
                items.add(item);
            }
            ((KmSearchResultObjVO) ((Result) result).getResult()).getKmSearchResultVOPage().setRecords(items);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) KmSearchResultObjVO(org.jeecg.common.system.vo.KmSearchResultObjVO) Date(java.util.Date) Result(org.jeecg.common.api.vo.Result) Field(java.lang.reflect.Field) IPage(com.baomidou.mybatisplus.core.metadata.IPage) JsonFormat(com.fasterxml.jackson.annotation.JsonFormat) JSONObject(com.alibaba.fastjson.JSONObject) Dict(org.jeecg.common.aspect.annotation.Dict) JSONObject(com.alibaba.fastjson.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SimpleDateFormat(java.text.SimpleDateFormat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with KmSearchResultObjVO

use of org.jeecg.common.system.vo.KmSearchResultObjVO in project kykms by mahonelau.

the class KmDocServiceImpl method searchESKmDoc.

/*
    普通检索
     */
public KmSearchResultObjVO searchESKmDoc(Page<KmSearchResultVO> page, KmDocEsParamVO kmDocEsParamVO, HttpServletRequest req) throws IOException {
    Map<String, String[]> parameterMap = req.getParameterMap();
    List<KmDocEsVO> kmDocEsVOList = new ArrayList<>();
    Page<KmSearchResultVO> resultVOPage = new Page<KmSearchResultVO>(page.getCurrent(), page.getSize());
    KmSearchResultObjVO kmSearchResultObjVO = new KmSearchResultObjVO();
    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
    if (sysUser == null) {
        kmSearchResultObjVO.setSuccess(false);
        kmSearchResultObjVO.setMessage("用户登陆信息异常");
        return kmSearchResultObjVO;
    }
    KmSearchRecord kmSearchRecord = new KmSearchRecord();
    // 在结果中检索的条件处理
    HttpSession session = req.getSession();
    // 最终条件
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    // 普通检索的条件,综合 : 标题、关键字、全文 合并检索
    BoolQueryBuilder boolQueryBuilderDefault = QueryBuilders.boolQuery();
    List<String> paramPaths = new ArrayList<>();
    List<String> keywords = new ArrayList<>();
    if (kmDocEsParamVO.getWithinSearchFlag() != null && kmDocEsParamVO.getWithinSearchFlag() == 1 && (session.getAttribute("searchParamsMust") != null || session.getAttribute("searchParamsFilter") != null || session.getAttribute("searchParamsShould") != null)) {
        // 历史参数处理,历史参数全部用filter
        Object paramObjMust = session.getAttribute("searchParamsMust");
        List<QueryBuilder> must = (List<QueryBuilder>) paramObjMust;
        if (must.size() > 0)
            must.forEach(e -> boolQueryBuilder.filter().add(e));
        Object paramObjFilter = session.getAttribute("searchParamsFilter");
        List<QueryBuilder> filter = (List<QueryBuilder>) paramObjFilter;
        if (filter.size() > 0)
            filter.forEach(e -> boolQueryBuilder.filter().add(e));
        Object paramObjShould = session.getAttribute("searchParamsShould");
        List<QueryBuilder> should = (List<QueryBuilder>) paramObjShould;
        if (should.size() > 0)
            should.forEach(e -> boolQueryBuilder.filter().add(e));
        // 参数路径处理
        Object pathObj = session.getAttribute("paramPaths");
        // Object  pathObj = redisUtil.get(KMConstant.SearchParamPrefix + userId + "_" + "paramPaths");
        if (pathObj != null) {
            List<String> historyParamPath = (List<String>) pathObj;
            if (historyParamPath.size() > 0) {
                for (String s : historyParamPath) {
                    paramPaths.add(s);
                }
            }
        }
        // 搜索关键字处理
        Object keywordObj = session.getAttribute("keywords");
        // Object  keywordObj = redisUtil.get(KMConstant.SearchParamPrefix + userId + "_" +  "keywords");
        if (keywordObj != null) {
            List<String> historyKeywords = (List<String>) keywordObj;
            if (historyKeywords.size() > 0) {
                for (String s : historyKeywords) {
                    keywords.add(s);
                }
            }
        }
    }
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    String paramPath = "";
    // 1、分类为必需条件 用filter
    if (kmDocEsParamVO.getCategory() != null) {
        paramPath = KMConstant.SearchTermSeprator + "分类: ";
        List<String> categorys = kmDocEsParamVO.getCategory();
        for (int i = 0; i < categorys.size(); i++) {
            paramPath = paramPath.concat(dictUtils.getDicText("km_dict_category", categorys.get(i)));
            paramPath = paramPath.concat(",");
        }
        paramPath = paramPath.substring(0, paramPath.length() - 1);
        boolQueryBuilder.filter().add(QueryBuilders.termsQuery("category", categorys));
    }
    // 2、标题检索 高级用must,高级用should
    if (kmDocEsParamVO.getTitle() != null && !kmDocEsParamVO.getTitle().isEmpty()) {
        paramPath = KMConstant.SearchTermSeprator + "标题: " + kmDocEsParamVO.getTitle() + paramPath;
        keywords.add(kmDocEsParamVO.getTitle());
        kmSearchRecord.setTitle(kmDocEsParamVO.getTitle());
        if (kmDocEsParamVO.getAdvSearchFlag() != null && kmDocEsParamVO.getAdvSearchFlag() == 1) {
            boolQueryBuilder.must().add(QueryBuilders.matchQuery("title", kmDocEsParamVO.getTitle()).analyzer("ik_smart").boost(kmConstant.getTitleSearchBoost()));
        } else {
            boolQueryBuilderDefault.should().add(QueryBuilders.matchQuery("title", kmDocEsParamVO.getTitle()).analyzer("ik_smart").boost(kmConstant.getTitleSearchBoost()));
        }
    }
    // 3、关键字检索 用term精确匹配;  高级用must,高级用should
    String keywordString = "";
    if (kmDocEsParamVO.getKeywords() != null && kmDocEsParamVO.getKeywords().size() > 0) {
        keywordString = String.join(",", kmDocEsParamVO.getKeywords());
        if ((kmDocEsParamVO.getTitle() != null && !kmDocEsParamVO.getTitle().isEmpty() && keywordString.equals(kmDocEsParamVO.getTitle())) || kmDocEsParamVO.getAdvSearchFlag() != 1) {
            paramPath = KMConstant.SearchTermSeprator + "关键字" + paramPath;
        } else {
            paramPath = KMConstant.SearchTermSeprator + "关键字: " + keywordString + paramPath;
        }
        keywords.addAll(kmDocEsParamVO.getKeywords().subList(0, kmDocEsParamVO.getKeywords().size()));
        kmSearchRecord.setKeywords(StringUtils.concatListToString(kmDocEsParamVO.getKeywords()));
        BoolQueryBuilder boolQueryBuilderKeywords = QueryBuilders.boolQuery();
        kmDocEsParamVO.getKeywords().forEach(e -> {
            boolQueryBuilderKeywords.should().add(QueryBuilders.termsQuery("keywords", e).boost(kmConstant.getKeywordSearchBoost()));
        });
        if (kmDocEsParamVO.getAdvSearchFlag() != null && kmDocEsParamVO.getAdvSearchFlag() == 1) {
            boolQueryBuilder.must().add(boolQueryBuilderKeywords);
        } else {
            boolQueryBuilderDefault.should().add(boolQueryBuilderKeywords);
        }
    }
    // 4、全文检索  高级用must,高级用should
    if (kmDocEsParamVO.getContent() != null && !kmDocEsParamVO.getContent().isEmpty()) {
        if ((keywordString != null && !keywordString.isEmpty() && keywordString.equals(kmDocEsParamVO.getContent())) || kmDocEsParamVO.getAdvSearchFlag() != 1) {
            paramPath = KMConstant.SearchTermSeprator + "全文" + paramPath;
        } else {
            paramPath = KMConstant.SearchTermSeprator + "全文: " + kmDocEsParamVO.getContent() + paramPath;
        }
        keywords.add(kmDocEsParamVO.getContent());
        kmSearchRecord.setContent(kmDocEsParamVO.getContent());
        if (kmDocEsParamVO.getAdvSearchFlag() != null && kmDocEsParamVO.getAdvSearchFlag() == 1) {
            boolQueryBuilder.must().add(QueryBuilders.matchQuery("content", kmDocEsParamVO.getContent()).analyzer("ik_smart").boost(kmConstant.getContentSearchBoost()));
        } else {
            boolQueryBuilderDefault.should().add(QueryBuilders.matchQuery("content", kmDocEsParamVO.getContent()).analyzer("ik_smart").boost(kmConstant.getContentSearchBoost()));
        }
    }
    // 处理普通检索的合并条件:标题、关键字、全文
    if (kmDocEsParamVO.getAdvSearchFlag() == null || kmDocEsParamVO.getAdvSearchFlag() == 0) {
        boolQueryBuilder.must().add(boolQueryBuilderDefault);
    }
    // 5、发布时间检索 用filter
    if (parameterMap.containsKey("pubTimeEnd")) {
        paramPath = KMConstant.SearchTermSeprator + "发布时间结束: " + kmDocEsParamVO.getPubTimeEnd() + paramPath;
        boolQueryBuilder.filter().add(QueryBuilders.rangeQuery("pubTime").lte(kmDocEsParamVO.getPubTimeEnd()));
    }
    if (parameterMap.containsKey("pubTimeStart")) {
        paramPath = KMConstant.SearchTermSeprator + "发布时间开始: " + kmDocEsParamVO.getPubTimeStart() + paramPath;
        boolQueryBuilder.filter().add(QueryBuilders.rangeQuery("pubTime").gte(kmDocEsParamVO.getPubTimeStart()));
    }
    // 6、来源检索 用filter
    if (kmDocEsParamVO.getSource() != null && !kmDocEsParamVO.getSource().isEmpty()) {
        String tmpSource = "";
        List<String> source = kmDocEsParamVO.getSource();
        for (int i = 0; i < source.size(); i++) {
            tmpSource = tmpSource.concat(dictUtils.getDicText("km_dict_source", source.get(i)));
            tmpSource = tmpSource.concat(",");
        }
        paramPath = KMConstant.SearchTermSeprator + "来源: " + tmpSource.substring(0, tmpSource.length() - 1) + paramPath;
        boolQueryBuilder.filter().add(QueryBuilders.termsQuery("source", source));
    }
    // 7、业务类型检索(多选) 用filter
    if (kmDocEsParamVO.getBusinessTypes() != null && kmDocEsParamVO.getBusinessTypes().size() > 0) {
        String tmpBusinessType = "";
        List<String> businessTypes = kmDocEsParamVO.getBusinessTypes();
        for (int i = 0; i < businessTypes.size(); i++) {
            tmpBusinessType = tmpBusinessType.concat(dictUtils.getDicText("km_dict_business", businessTypes.get(i)));
            tmpBusinessType = tmpBusinessType.concat(",");
        }
        paramPath = KMConstant.SearchTermSeprator + "业务类型: " + tmpBusinessType.substring(0, tmpBusinessType.length() - 1) + paramPath;
        boolQueryBuilder.filter().add(QueryBuilders.termsQuery("businessTypes", businessTypes));
    }
    // 8、版本状态检索(多选) 用filter
    if (kmDocEsParamVO.getVersions() != null && kmDocEsParamVO.getVersions().size() > 0) {
        String tmpVersion = "";
        List<String> versions = kmDocEsParamVO.getVersions();
        for (int i = 0; i < versions.size(); i++) {
            tmpVersion = tmpVersion.concat(dictUtils.getDicText("km_dict_versions", versions.get(i)));
            tmpVersion = tmpVersion.concat(",");
        }
        paramPath = KMConstant.SearchTermSeprator + "版本: " + tmpVersion.substring(0, tmpVersion.length() - 1) + paramPath;
        boolQueryBuilder.filter().add(QueryBuilders.termsQuery("versions", versions));
    }
    // 9、专题检索(多选,前缀模糊匹配) 用filter
    if (kmDocEsParamVO.getTopicCodes() != null && kmDocEsParamVO.getTopicCodes().size() > 0) {
        String tmpTopicCodes = "";
        kmSearchRecord.setTopicCodes(StringUtils.concatListToString(kmDocEsParamVO.getTopicCodes()));
        BoolQueryBuilder boolQueryBuilderTopicCodes = QueryBuilders.boolQuery();
        List<String> topicCodes = kmDocEsParamVO.getTopicCodes();
        for (int i = 0; i < topicCodes.size(); i++) {
            // 模糊匹配,匹配某个字符串开头的记录prefixQuery
            boolQueryBuilderTopicCodes.should().add(QueryBuilders.prefixQuery("topicCodes", topicCodes.get(i)));
            String topicName = sysBaseAPI.queryCategoryNameByCode(topicCodes.get(i));
            if (topicName != null)
                tmpTopicCodes = tmpTopicCodes.concat(topicName);
            else
                tmpTopicCodes = tmpTopicCodes.concat(topicCodes.get(i));
            tmpTopicCodes = tmpTopicCodes.concat(",");
        }
        paramPath = KMConstant.SearchTermSeprator + "专题: " + tmpTopicCodes.substring(0, tmpTopicCodes.length() - 1) + paramPath;
        boolQueryBuilder.filter().add(boolQueryBuilderTopicCodes);
    }
    // 10、文号,(前缀模糊匹配) 用filter
    if (kmDocEsParamVO.getFileNo() != null && !kmDocEsParamVO.getFileNo().isEmpty()) {
        paramPath = KMConstant.SearchTermSeprator + "文号: " + kmDocEsParamVO.getFileNo() + paramPath;
        boolQueryBuilder.filter().add(QueryBuilders.wildcardQuery("fileNo", kmDocEsParamVO.getFileNo()));
    }
    // 去掉检索参数第一个+
    if (!paramPath.isEmpty() && paramPath.length() > 3)
        paramPath = paramPath.substring(3);
    // 11、发布状态必须为1
    boolQueryBuilder.filter().add(QueryBuilders.termQuery("releaseFlag", 1));
    // 排序,对字典文本字段,去掉后缀
    if (kmDocEsParamVO.getColumn() != null && !kmDocEsParamVO.getColumn().isEmpty() && kmDocEsParamVO.getOrder() != null && !kmDocEsParamVO.getOrder().isEmpty()) {
        String column = kmDocEsParamVO.getColumn();
        String order = kmDocEsParamVO.getOrder();
        if (column.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) {
            column = column.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX));
        }
        // if(column.equals("pubTimeTxt")) {
        // column = "pubTime";
        // }
        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort(column).order(SortOrder.fromString(order));
        searchSourceBuilder.sort(fieldSortBuilder);
    }
    searchSourceBuilder.query(boolQueryBuilder);
    // highlight field 仅对title
    HighlightBuilder highlightBuilder = new HighlightBuilder().field("title").requireFieldMatch(false);
    highlightBuilder.preTags("<span style=\"color:blue\">");
    highlightBuilder.postTags("</span>");
    searchSourceBuilder.highlighter(highlightBuilder);
    // 分页
    // 注意分页的坑,from要从0开始
    long from = page.getCurrent() < 1 ? 0 : page.getSize() * (page.getCurrent() - 1);
    long size = page.getSize() > 100 ? 100 : page.getSize();
    size = size < 0 ? 10 : size;
    searchSourceBuilder.from((int) from);
    searchSourceBuilder.size((int) size);
    // 超时 60S
    searchSourceBuilder.timeout(new TimeValue(KMConstant.SearchTimeOutSeconds, TimeUnit.SECONDS));
    // 过滤返回结果字段,去掉非必要信息,关键:去掉content
    // {"content","keywords"};
    String[] excludeFields = { "content" };
    // {"id","title","source","versions","pubTime"};
    String[] includeFields = {};
    searchSourceBuilder.fetchSource(includeFields, excludeFields);
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.source(searchSourceBuilder);
    searchRequest.indices(KMConstant.DocIndexAliasName);
    log.debug(searchRequest.source().toString());
    // 分页、排序变换的时候不更新session,历史条件不叠加
    if (paramPaths == null || paramPaths.size() == 0 || !paramPaths.get(paramPaths.size() - 1).equals(paramPath)) {
        paramPaths.add(paramPath);
        session.setAttribute("searchParamsMust", boolQueryBuilder.must());
        session.setAttribute("searchParamsFilter", boolQueryBuilder.filter());
        session.setAttribute("searchParamsShould", boolQueryBuilder.should());
        session.setAttribute("paramPaths", paramPaths);
        session.setAttribute("keywords", keywords);
    }
    kmSearchResultObjVO.setParamPath(paramPaths);
    SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    if (searchResponse.status() != RestStatus.OK || searchResponse.getHits().getTotalHits().value <= 0) {
        kmSearchResultObjVO.setKmSearchResultVOPage(resultVOPage);
        kmSearchResultObjVO.setSuccess(true);
    } else {
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            log.debug(hit.getSourceAsString());
            KmDocEsVO kmDocEsVO = JSON.parseObject(hit.getSourceAsString(), KmDocEsVO.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            // 获取title高亮显示
            if (highlightFields != null && highlightFields.size() > 0) {
                HighlightField highlight = highlightFields.get("title");
                // 获取高亮显示的字段
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                kmDocEsVO.setTitle(fragmentString);
            }
            kmDocEsVOList.add(kmDocEsVO);
        }
        List<KmSearchResultVO> kmSearchResultVOList = retrieveDocDbInfo(kmDocEsVOList);
        resultVOPage.setRecords(kmSearchResultVOList);
        // set page
        resultVOPage.setTotal(hits.getTotalHits().value);
        resultVOPage.setHitCount(hits.getTotalHits().value > 0);
        kmSearchResultObjVO.setKmSearchResultVOPage(resultVOPage);
        kmSearchResultObjVO.setSuccess(true);
    }
    // 日志和限制
    executorService.execute(() -> kmSearchRecordService.logSearch(kmSearchRecord.getKeywords(), kmSearchRecord.getTitle(), kmSearchRecord.getContent(), kmSearchRecord.getTopicCodes(), IpUtils.getIpAddr(req)));
    return kmSearchResultObjVO;
}
Also used : SortBuilders(org.elasticsearch.search.sort.SortBuilders) SearchHits(org.elasticsearch.search.SearchHits) Autowired(org.springframework.beans.factory.annotation.Autowired) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) Session(org.apache.shiro.session.Session) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) KM.service(org.jeecg.modules.KM.service) KM.common.enums(org.jeecg.modules.KM.common.enums) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) JSONConfig(cn.hutool.json.JSONConfig) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) KMConstant(org.jeecg.modules.KM.common.rules.KMConstant) SearchResponse(org.elasticsearch.action.search.SearchResponse) RequestOptions(org.elasticsearch.client.RequestOptions) TransactionAspectSupport(org.springframework.transaction.interceptor.TransactionAspectSupport) BigInteger(java.math.BigInteger) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) KmDocMapper(org.jeecg.modules.KM.mapper.KmDocMapper) ParseException(java.text.ParseException) SearchHit(org.elasticsearch.search.SearchHit) ServiceImpl(com.baomidou.mybatisplus.extension.service.impl.ServiceImpl) HttpSession(javax.servlet.http.HttpSession) QueryGenerator(org.jeecg.common.system.query.QueryGenerator) JSONObject(cn.hutool.json.JSONObject) FieldSortBuilder(org.elasticsearch.search.sort.FieldSortBuilder) RedisUtil(org.jeecg.common.util.RedisUtil) Slf4j(lombok.extern.slf4j.Slf4j) RestStatus(org.elasticsearch.rest.RestStatus) SortOrder(org.elasticsearch.search.sort.SortOrder) CommonConstant(org.jeecg.common.constant.CommonConstant) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SecurityUtils(org.apache.shiro.SecurityUtils) DatePattern(cn.hutool.core.date.DatePattern) CommonUtils(org.jeecg.common.util.CommonUtils) BeanUtils(org.springframework.beans.BeanUtils) KM.common.utils(org.jeecg.modules.KM.common.utils) java.util(java.util) XContentType(org.elasticsearch.common.xcontent.XContentType) SerialNumberRule(org.jeecg.modules.KM.common.rules.SerialNumberRule) SearchRequest(org.elasticsearch.action.search.SearchRequest) HighlightBuilder(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) WriteRequest(org.elasticsearch.action.support.WriteRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) LoginUser(org.jeecg.common.system.vo.LoginUser) Subject(org.apache.shiro.subject.Subject) Text(org.elasticsearch.common.text.Text) Propagation(org.springframework.transaction.annotation.Propagation) ServletOutputStream(javax.servlet.ServletOutputStream) Service(org.springframework.stereotype.Service) TimeValue(org.elasticsearch.common.unit.TimeValue) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) HighlightField(org.elasticsearch.search.fetch.subphase.highlight.HighlightField) IndexResponse(org.elasticsearch.action.index.IndexResponse) VO(org.jeecg.modules.KM.VO) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BaseConfig(org.jeecg.modules.KM.common.config.BaseConfig) Result(org.jeecg.common.api.vo.Result) ISysBaseAPI(org.jeecg.common.system.api.ISysBaseAPI) HttpServletResponse(javax.servlet.http.HttpServletResponse) KM.entity(org.jeecg.modules.KM.entity) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) UUIDGenerator(org.jeecg.common.util.UUIDGenerator) TimeUnit(java.util.concurrent.TimeUnit) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) HttpStatus(org.springframework.http.HttpStatus) URLEncoder(java.net.URLEncoder) JSON(com.alibaba.fastjson.JSON) java.io(java.io) KmSearchResultObjVO(org.jeecg.common.system.vo.KmSearchResultObjVO) DateUtils(org.jeecg.common.util.DateUtils) Transactional(org.springframework.transaction.annotation.Transactional) SearchRequest(org.elasticsearch.action.search.SearchRequest) SearchHit(org.elasticsearch.search.SearchHit) KmSearchResultObjVO(org.jeecg.common.system.vo.KmSearchResultObjVO) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) LoginUser(org.jeecg.common.system.vo.LoginUser) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchHits(org.elasticsearch.search.SearchHits) TimeValue(org.elasticsearch.common.unit.TimeValue) HttpSession(javax.servlet.http.HttpSession) FieldSortBuilder(org.elasticsearch.search.sort.FieldSortBuilder) HighlightField(org.elasticsearch.search.fetch.subphase.highlight.HighlightField) Text(org.elasticsearch.common.text.Text) SearchResponse(org.elasticsearch.action.search.SearchResponse) JSONObject(cn.hutool.json.JSONObject) HighlightBuilder(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder)

Example 4 with KmSearchResultObjVO

use of org.jeecg.common.system.vo.KmSearchResultObjVO in project kykms by mahonelau.

the class KmDocController method searchDoc.

@ApiOperation(value = "km_doc-普通检索", notes = "km_doc-普通检索")
@GetMapping(value = "/searchDoc")
public Result<?> searchDoc(KmDocEsParamVO kmDocEsParamVO, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
    try {
        if (kmDocEsParamVO.getKeywords() != null && kmDocEsParamVO.getKeywords().size() > 0) {
            kmDocEsParamVO.setKeywords(StringUtils.splitStrListToList(kmDocEsParamVO.getKeywords()));
        }
        Page<KmSearchResultVO> page = new Page<KmSearchResultVO>(pageNo, pageSize);
        KmSearchResultObjVO kmSearchResultObjVO = kmDocService.searchESKmDoc(page, kmDocEsParamVO, req);
        if (kmSearchResultObjVO.isSuccess()) {
            dictUtils.parseDictText(kmSearchResultObjVO);
            return Result.OK(kmSearchResultObjVO);
        } else
            return Result.error(kmSearchResultObjVO.getMessage());
    } catch (IOException e) {
        return Result.error(e.getMessage());
    }
}
Also used : KmSearchResultObjVO(org.jeecg.common.system.vo.KmSearchResultObjVO) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) IPage(com.baomidou.mybatisplus.core.metadata.IPage) ApiOperation(io.swagger.annotations.ApiOperation)

Example 5 with KmSearchResultObjVO

use of org.jeecg.common.system.vo.KmSearchResultObjVO in project kykms by mahonelau.

the class DictAspect method parseDictText.

/**
 * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
 * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
 * 示例为SysUser   字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
 * 例输入当前返回值的就会多出一个sex_dictText字段
 * {
 *      sex:1,
 *      sex_dictText:"男"
 * }
 * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
 *  customRender:function (text) {
 *               if(text==1){
 *                 return "男";
 *               }else if(text==2){
 *                 return "女";
 *               }else{
 *                 return text;
 *               }
 *             }
 *             目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
 * @param result
 */
private void parseDictText(Object result) {
    if (result instanceof Result) {
        if (((Result) result).getResult() instanceof IPage) {
            List<JSONObject> items = new ArrayList<>();
            for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    // 解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                JSONObject item = JSONObject.parseObject(json);
                // for (Field field : record.getClass().getDeclaredFields()) {
                for (Field field : oConvertUtils.getAllFields(record)) {
                    // update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    if (field.getAnnotation(Dict.class) != null) {
                        String code = field.getAnnotation(Dict.class).dicCode();
                        String text = field.getAnnotation(Dict.class).dicText();
                        String table = field.getAnnotation(Dict.class).dictTable();
                        String key = String.valueOf(item.get(field.getName()));
                        // 翻译字典值对应的txt
                        String textValue = translateDictValue(code, text, table, key);
                        log.debug(" 字典Val : " + textValue);
                        log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                        item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                    }
                    // date类型默认转换string格式化日期
                    if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                        SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                    }
                }
                items.add(item);
            }
            ((IPage) ((Result) result).getResult()).setRecords(items);
        } else if (((Result) result).getResult() instanceof KmSearchResultObjVO) {
            List<JSONObject> items = new ArrayList<>();
            for (Object record : ((KmSearchResultObjVO) ((Result) result).getResult()).getKmSearchResultVOPage().getRecords()) {
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    // 解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                JSONObject item = JSONObject.parseObject(json);
                // for (Field field : record.getClass().getDeclaredFields()) {
                for (Field field : oConvertUtils.getAllFields(record)) {
                    // update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    if (field.getAnnotation(Dict.class) != null) {
                        String code = field.getAnnotation(Dict.class).dicCode();
                        String text = field.getAnnotation(Dict.class).dicText();
                        String table = field.getAnnotation(Dict.class).dictTable();
                        String key = String.valueOf(item.get(field.getName()));
                        // 翻译字典值对应的txt
                        String textValue = translateDictValue(code, text, table, key);
                        log.debug(" 字典Val : " + textValue);
                        log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
                        item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                    }
                    // date类型默认转换string格式化日期
                    if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                        SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                    }
                }
                items.add(item);
            }
            ((KmSearchResultObjVO) ((Result) result).getResult()).getKmSearchResultVOPage().setRecords(items);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) KmSearchResultObjVO(org.jeecg.common.system.vo.KmSearchResultObjVO) Date(java.util.Date) Result(org.jeecg.common.api.vo.Result) Field(java.lang.reflect.Field) IPage(com.baomidou.mybatisplus.core.metadata.IPage) JsonFormat(com.fasterxml.jackson.annotation.JsonFormat) JSONObject(com.alibaba.fastjson.JSONObject) Dict(org.jeecg.common.aspect.annotation.Dict) JSONObject(com.alibaba.fastjson.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SimpleDateFormat(java.text.SimpleDateFormat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

KmSearchResultObjVO (org.jeecg.common.system.vo.KmSearchResultObjVO)10 Page (com.baomidou.mybatisplus.extension.plugins.pagination.Page)8 IPage (com.baomidou.mybatisplus.core.metadata.IPage)6 ApiOperation (io.swagger.annotations.ApiOperation)4 SearchRequest (org.elasticsearch.action.search.SearchRequest)4 SearchResponse (org.elasticsearch.action.search.SearchResponse)3 Text (org.elasticsearch.common.text.Text)3 TimeValue (org.elasticsearch.common.unit.TimeValue)3 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)3 SearchHit (org.elasticsearch.search.SearchHit)3 SearchHits (org.elasticsearch.search.SearchHits)3 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)3 HighlightBuilder (org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder)3 HighlightField (org.elasticsearch.search.fetch.subphase.highlight.HighlightField)3 FieldSortBuilder (org.elasticsearch.search.sort.FieldSortBuilder)3 Result (org.jeecg.common.api.vo.Result)3 LoginUser (org.jeecg.common.system.vo.LoginUser)3 DatePattern (cn.hutool.core.date.DatePattern)2 JSONConfig (cn.hutool.json.JSONConfig)2 JSONObject (cn.hutool.json.JSONObject)2