赞
踩
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;
//TestIndexSearchQuery query为条件查询对象,封装了一些需要查询的字段
@Override
public Page<TestIndex> search(TestIndexSearchQuery query) {
Integer pageNum = query.getPageNum();
Integer pageSize = query.getPageSize();
//组装查询条件
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
//user_id = Xa
if(StringUtils.isNotBlank(query.getXa())){
queryBuilder.must(termQuery("user_id", query.getXa()));
}
//这里的say_words的ES type为text,是支持分词查询的
if(StringUtils.isNotBlank(query.getXb())){
queryBuilder.must(queryStringQuery(query.getXb()).field("say_words"));
}
//载入查询对象
NativeSearchQuery build = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
.withSort(SortBuilders.fieldSort("say_time").order(SortOrder.DESC)) //排序
.withPageable(PageRequest.of(pageNum, pageSize))
.withHighlightFields(//字段高亮设值
new HighlightBuilder.Field("say_words").preTags("<em>").postTags("</em>")
// new HighlightBuilder.Field("say_words").preTags("<span style='color:blue'>").postTags("</span>")
)
.build();
LOGGER.debug("模糊查询的语句:", build.getQuery().toString());
SearchHits<TestIndex> search = elasticsearchRestTemplate.search(build, TestIndex.class);
SearchPage<TestIndex> page = SearchHitSupport.searchPageFor(search, build.getPageable());
//高亮结果集,也可以用page.getHighlightFields()获取
List<Seek> list = new ArrayList<>();
for (SearchHit<TestIndex> each : page) {
TestIndex vo = each.getContent();
//高亮设值
if (each.getHighlightFields().get("say_words") != null) {
vo.setSeek_title(each.getHighlightFields().get("say_words").get(0));
}
list.add(vo);
}
//组装分页对象
Page<TestIndex> pageInfo = new PageImpl<>(list, build.getPageable(), search.getTotalHits());
// PageImpl<TestIndex> pageInfo = new PageImpl<TestIndex>(list, build.getPageable(), search.getTotalHits());
return pageInfo;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。