TIPS:本文实现类似数据库后台管理系统的多条件分页查询。文章来源地址https://www.toymoban.com/news/detail-509677.html
package com.test.impl;
/**
* TestIndex实现类impl,实现多条件分页查询
*/
@Service
public class TestIndexServiceImpl implements TestIndexService {
private static final Logger LOGGER = LoggerFactory.getLogger(TestIndexServiceImpl.class);
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
//TestIndexListQuery query为条件查询对象,封装了一些需要查询的字段
@Override
public Page<TestIndex> list(TestIndexListQuery query) {
Integer pageNum = query.getPageNum();
Integer pageSize = query.getPageSize();
//组装查询条件 must类似and匹配到所有字段后进行组合查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if(StringUtils.isNotBlank(query.getItem_id())){
queryBuilder.must(termQuery("item_id", query.getItem_id()));
}
if(StringUtils.isNotBlank(query.getItem_name())){
//类似like的操作,针对不能分词的字段进行模糊查询,数据量大不推荐,性能不友好
queryBuilder.must(wildcardQuery("item_name", "*"+query.getItem_name()+"*"));
}
if(StringUtils.isNotBlank(query.getArea_code())){
queryBuilder.must(termQuery("area_code", query.getArea_code()));
}
if(StringUtils.isNotBlank(query.getUser_name())){
queryBuilder.must(QueryBuilders.wildcardQuery("user_name", "*"+query.getUser_name()+"*"));
}
if(StringUtils.isNotBlank(query.getPhone())){
queryBuilder.must(termQuery("phone", query.getPhone()));
}
if (Objects.nonNull(query.getStartTime())) {
queryBuilder.must(QueryBuilders.rangeQuery("createdatetime").gte(query.getStartTime()));
}
if (Objects.nonNull(query.getEndTime())) {
queryBuilder.must(QueryBuilders.rangeQuery("createdatetime").lte(query.getEndTime()));
}
NativeSearchQuery build = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
.withPageable(PageRequest.of(pageNum, pageSize))
.withHighlightFields(//字段高亮设值
new HighlightBuilder.Field("seek_title").preTags("<em>").postTags("</em>")
// new HighlightBuilder.Field("seek_title").preTags("<span style='color:blue'>").postTags("</span>")
)
.build();
LOGGER.info("列表查询的语句:{}", build.getQuery().toString());
SearchHits<Seek> search = elasticsearchRestTemplate.search(build, Seek.class);
SearchPage<Seek> page = SearchHitSupport.searchPageFor(search, build.getPageable());
//高亮结果集,也可以用page.getHighlightFields()获取
List<Seek> list = new ArrayList<>();
for (SearchHit<Seek> each : page) {
Seek vo = each.getContent();
//高亮设值
if (each.getHighlightFields().get("seek_title") != null) {
vo.setSeek_title(each.getHighlightFields().get("seek_title").get(0));
}
list.add(vo);
}
//组装分页对象
Page<Seek> pageInfo = new PageImpl<>(list, build.getPageable(), search.getTotalHits());
// PageImpl<Seek> pageInfo = new PageImpl<Seek>(list, build.getPageable(), search.getTotalHits());
return pageInfo;
}
}
文章来源:https://www.toymoban.com/news/detail-509677.html
到了这里,关于ES简单教程(四)使用ElasticsearchRestTemplate多条件分页查询(复杂版)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!