赞
踩
TIPS:本文实现类似数据库后台管理系统的多条件分页查询。
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;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。