• SpringBoot中ElasticsearchRestTemplate的使用示例,(增删改查、高亮查询、id查询、分页查询、时间范围查询、多条件查询)


    前言

    最近在单位搞日志相关的东西,然后部分日志就存储到了elasticsearch索引库,慢慢发觉索引库用着是真香,写这篇文章的目的就是记录一下关于ElasticsearchRestTemplate Api的使用

    🐳创建索引并推送映射

    /**
     * 创建索引并推送映射
     * @return
     */
    @Override
    public boolean createIndexAndPushMapping() {
    
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Item.class);
        //创建索引
        boolean a = indexOperations.create();
        if (a){
            //生成映射
            Document mapping = indexOperations.createMapping();
            //推送映射
            boolean b = indexOperations.putMapping(mapping);
            return b;
        }else {
            return a;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

    在这里插入图片描述


    🍒删除索引

    /**
     * 删除索引
     * @param index
     * @return
     */
    @Override
    public boolean deleteIndex(String index) {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Item.class);
        boolean delete = indexOperations.delete();
        return delete;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述
    在这里插入图片描述


    🐳添加或修改文档

    /**
     * 添加或修改文档
     * @param index
     * @return
     */
    @Override
    public boolean addOrUpdate(Item item,String index) {
    
        item.setTime(new Date());
    
        try {
            elasticsearchRestTemplate.save(item, IndexCoordinates.of(index));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述
    在这里插入图片描述


    🍒根据id删除文档

    /**
     * 删除文档
     * @param index
     * @return
     */
    @Override
    public boolean delete(String id,String index) {
    
        try {
            elasticsearchRestTemplate.delete(id, IndexCoordinates.of(index));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return false;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述


    🌳根据id查询

    /**
     * 根据id查询
     *
     * @param id
     * @param index
     * @return
     */
    @Override
    public ItemVO selectAllById(String id, String index) {
    
        IdsQueryBuilder idsQueryBuilder = QueryBuilders.idsQuery();
        idsQueryBuilder.addIds(id);
    
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(idsQueryBuilder)
                .build();
    
        SearchHit<ItemVO> itemSearchHit = elasticsearchRestTemplate.searchOne(query, ItemVO.class, IndexCoordinates.of(index));
        ItemVO content = itemSearchHit.getContent();
        return content;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述


    🐸高亮查询

    /**
     * 高亮查询
     * @param keyword
     * @param index
     * @return
     */
    @Override
    public List<ItemVO> searchHighlight(String keyword, String index) {
        ArrayList<ItemVO> itemVOS = new ArrayList<>();
    
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("requestBody", keyword);
    
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("requestBody");
        highlightBuilder.requireFieldMatch(false);//多个高亮关闭
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
    
    
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(matchQueryBuilder)
                .build();
        query.setHighlightQuery(new HighlightQuery(highlightBuilder));
    
        SearchHits<ItemVO> search = elasticsearchRestTemplate.search(query, ItemVO.class, IndexCoordinates.of(index));
        
        for (SearchHit<ItemVO> searchHit : search) {
            ItemVO content = searchHit.getContent();
            //将高亮的字段取出来
            List<String> requestBody = searchHit.getHighlightField("requestBody");
            String highText = "";
            for (String s : requestBody) {
                highText = highText += s;
            }
            //重新对字段赋值
            content.setRequestBody(highText);
            itemVOS.add(content);
        }
        return itemVOS;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在这里插入图片描述


    🍈分页查询

    /**
     * 分页查询
     * @param page
     * @param size
     * @param index
     * @return
     */
    @Override
    public List<ItemVO> selectByPage(int page, int size,String index) {
    
        List<ItemVO> itemVOS = new ArrayList<>();
    
        try {
            NativeSearchQuery query = new NativeSearchQueryBuilder().withPageable(PageRequest.of(page - 1, size))
                    .build();
    
            SearchHits<ItemVO> search = elasticsearchRestTemplate.search(query, ItemVO.class, IndexCoordinates.of(index));
    
            search.forEach((hits)->itemVOS.add(hits.getContent()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return itemVOS;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述


    🌴数据排序

    /**
     * 排序查询
     * @param index
     * @return
     */
    @Override
    public List<ItemVO> selectByTimeDesc(String index) {
        List<ItemVO> itemVOS = new ArrayList<>();
    
        try {
            NativeSearchQuery query = new NativeSearchQueryBuilder().withSort(SortBuilders.fieldSort("time").order(SortOrder.DESC))
                    .build();
    
            SearchHits<ItemVO> search = elasticsearchRestTemplate.search(query, ItemVO.class, IndexCoordinates.of(index));
    
            search.forEach((hits)->itemVOS.add(hits.getContent()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return itemVOS;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述


    🏝️时间区间查询

    /**
     * 时间区间查询
     * @param begin
     * @param end
     * @param index
     * @return
     */
    @Override
    public List<ItemVO> selectByTimeFromTo(String begin, String end, String index) {
        List<ItemVO> itemVOS = new ArrayList<>();
    
        try {
            NativeSearchQuery query = new NativeSearchQueryBuilder().withSort(SortBuilders.fieldSort("time").order(SortOrder.DESC))
                    .withFilter(QueryBuilders.rangeQuery("time").timeZone("+08:00").format("yyyy-MM-dd HH:mm:ss").gt(begin).lt(end))
                    .build();
    
            SearchHits<ItemVO> search = elasticsearchRestTemplate.search(query, ItemVO.class, IndexCoordinates.of(index));
    
            search.forEach((hits) -> itemVOS.add(hits.getContent()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return itemVOS;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述

    🐴多条件查询示例例

    public BaseQueryPageVO<List<LogDataVO>> searchApiLogData(LogDataPageDTO logDataPageDTO) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        ArrayList<LogDataDO> logDataDOS = new ArrayList<>();
    
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder
                .filter(QueryBuilders.rangeQuery("time").timeZone("+08:00").format("yyyy-MM-dd HH:mm:ss").gt(logDataPageDTO.getBegin()).lt(logDataPageDTO.getEnd()))
                .must(QueryBuilders.matchQuery("requestBody", logDataPageDTO.getKeyword()));
    
    
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withSort(SortBuilders.fieldSort("time").order(SortOrder.DESC))
                .withPageable(PageRequest.of(logDataPageDTO.getCurrent()-1,logDataPageDTO.getSize()))
                .withQuery(boolQueryBuilder)
                .build();
    
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("requestBody");
        highlightBuilder.requireFieldMatch(false);//多个高亮关闭
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        // 返回实际命中数
        searchQuery.setTrackTotalHits(true);
        searchQuery.setHighlightQuery(new HighlightQuery(highlightBuilder));
    
        SearchHits<LogDataDO> search = elasticsearchRestTemplate.search(searchQuery, LogDataDO.class, IndexCoordinates.of(logDataPageDTO.getIndexName()));
    
        List<SearchHit<LogDataDO>> searchHits = search.getSearchHits();
        for (SearchHit<LogDataDO> searchHit : searchHits) {
            LogDataDO content = searchHit.getContent();
    
            List<String> requestBody = searchHit.getHighlightField("requestBody");
            String highText = "";
            for (String s : requestBody) {
                highText = highText += s;
            }
            content.setResultData(null);
            content.setRequestBody(highText);
            logDataDOS.add(content);
        }
    
        BaseQueryPageVO baseQueryPageVO = new BaseQueryPageVO();
        baseQueryPageVO.setTotal(search.getTotalHits());
        baseQueryPageVO.setSize(Long.valueOf(logDataPageDTO.getSize()));
        baseQueryPageVO.setCurrent(Long.valueOf(logDataPageDTO.getCurrent()));
        baseQueryPageVO.setTotal(search.getTotalHits());
        baseQueryPageVO.setRecords(CopyUtils.do2DtoList(logDataDOS, LogDataVO.class));
    
        return baseQueryPageVO;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
  • 相关阅读:
    go的日志库logrus
    LabVIEW前面板和程序框图的最大尺寸
    解决更换NodeJs版本后npm -v返回空白
    IOC操作Bean管理(基于注解方式)
    计算机网络(持续更新…)
    Docker 搭建 LNMP + Wordpress(详细步骤)
    No8.【spring-cloud-alibaba】基于OAuth2,新增加手机号验证码登录模式(不包含发短信,还没找到合适的短信发送平台)
    开源模型应用落地-FastAPI-助力模型交互-WebSocket篇(五)
    人工智能在电子商务中的突破性优势
    【python笔记】第九节 函数进阶
  • 原文地址:https://blog.csdn.net/weixin_43627706/article/details/126061049