Example of using ElasticsearchRestTemplate in SpringBoot, (add, delete, modify, highlight, id, paginate, time range, and multi-condition queries)

fate strikes fast 2022-08-06 17:27:04 阅读数:441

exampleusingelasticsearchresttemplatespringbootadd

前言

Recently, I have been working on log related things in the unit,Then part of the log is storedelasticsearch索引库,Slowly found that the index library is really fragrant,The purpose of writing this article is to record aboutElasticsearchRestTemplate Api的使用

Create the index and push the map

/** * Create the index and push the map * @return */
@Override
public boolean createIndexAndPushMapping() {

IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Item.class);
//创建索引
boolean a = indexOperations.create();
if (a){

//生成映射
Document mapping = indexOperations.createMapping();
//push map
boolean b = indexOperations.putMapping(mapping);
return b;
}else {

return a;
}
}

在这里插入图片描述

在这里插入图片描述


删除索引

/** * 删除索引 * @param index * @return */
@Override
public boolean deleteIndex(String index) {

IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Item.class);
boolean delete = indexOperations.delete();
return delete;
}

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


添加或修改文档

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

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


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

在这里插入图片描述


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

在这里插入图片描述


高亮查询

/** * 高亮查询 * @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("<span style='color:red'>");
highlightBuilder.postTags("</span>");
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();
//Take out the highlighted field
List<String> requestBody = searchHit.getHighlightField("requestBody");
String highText = "";
for (String s : requestBody) {

highText = highText += s;
}
//Reassign the field
content.setRequestBody(highText);
itemVOS.add(content);
}
return itemVOS;
}

在这里插入图片描述


分页查询

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

在这里插入图片描述


数据排序

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

在这里插入图片描述


️时间区间查询

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

在这里插入图片描述

Example of multi-condition query

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("<span style='color:red'>");
highlightBuilder.postTags("</span>");
// 返回实际命中数
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;
}
copyright:author[fate strikes fast],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/218/202208061703203432.html