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

前言

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

  • 下载及整合ElasticSearch SpringBoot2.3.x整合ElasticSearch

创建索引并推送映射

/**
 * 创建索引并推送映射
 * @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;
    }
}

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

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


删除索引

/**
 * 删除索引
 * @param index
 * @return
 */
@Override
public boolean deleteIndex(String index) {
    IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Item.class);
    boolean delete = indexOperations.delete();
    return delete;
}

SpringBoot中ElasticsearchRestTemplate的使用示例,(增删改查、高亮查询、id查询、分页查询、时间范围查询、多条件查询)_第3张图片
SpringBoot中ElasticsearchRestTemplate的使用示例,(增删改查、高亮查询、id查询、分页查询、时间范围查询、多条件查询)_第4张图片


添加或修改文档

/**
 * 添加或修改文档
 * @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;
}

SpringBoot中ElasticsearchRestTemplate的使用示例,(增删改查、高亮查询、id查询、分页查询、时间范围查询、多条件查询)_第5张图片
SpringBoot中ElasticsearchRestTemplate的使用示例,(增删改查、高亮查询、id查询、分页查询、时间范围查询、多条件查询)_第6张图片


根据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;
}

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


根据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;
}

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


高亮查询

/**
 * 高亮查询
 * @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;
}

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


分页查询

/**
 * 分页查询
 * @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;
}

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


数据排序

/**
 * 排序查询
 * @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;
}

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


️时间区间查询

/**
 * 时间区间查询
 * @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;
}

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

多条件查询示例例

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;
}


你可能感兴趣的:(SpringBoot,Elasticsearch,spring,boot,java,spring,elasticsearch)