es的scroll api使用

该博客主要介绍了如何使用Elasticsearch的Scroll API进行分页搜索。通过创建一个`FacetedPageWithScore`对象并映射`SearchResponse`来获取`SearchResume`对象,同时处理每个搜索结果的分数,避免出现NaN异常。在处理过程中,将搜索结果存储到HashMap中,并为每个结果创建带有分数的`SearchResumeWithScore`对象。
摘要由CSDN通过智能技术生成

MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("app",app);
        SearchQuery query = new NativeSearchQueryBuilder()
                .withIndices(index)
                .withTypes(type)
                .withQuery(matchQueryBuilder)
                .withPageable(page)
                .build();
        long scollTimeInMillis = 1000;
        String scrollId = elasticsearchTemplate.scan(query, scollTimeInMillis, false);
        boolean hasRecords = true;
        long totalCount = 0;
        while (hasRecords) {
            Page<LogDetail> page = elasticsearchTemplate.scroll(scrollId, scollTimeInMillis, LogDetail.class);
            if (page.hasContent()) {
                LOGGER.info("page number:{}",page.getNumberOfElements());
                totalCount += page.getNumberOfElements();
            } else {
                hasRecords = false;
            }
        }

        //clear scroll
        elasticsearchTemplate.clearScroll(scrollId);
public FacetedPageWithScore searchResumeByConditionForPage(final SearchQuery searchQuery) {
return elasticsearchTemplate.query(searchQuery, new ResultsExtractor<FacetedPageWithScore>() {
@Override
public FacetedPageWithScore extract(SearchResponse response) {
final List<SearchResumeWithScore> scoreResumeList = new ArrayList<>();
ResultsMapper mapper = new DefaultResultMapper(elasticsearchTemplate.getElasticsearchConverter().getMappingContext());
FacetedPage<SearchResume> searchResult = mapper.mapResults(response, SearchResume.class, searchQuery.getPageable());
List<SearchResume> content = searchResult.getContent();
Map<Long, SearchResume> mapSearchResume = new HashMap<>();
for (SearchResume searchResume: content){
mapSearchResume.put(searchResume.getId(), searchResume);
}

SearchHits searchHits = response.getHits();
for(SearchHit searchhit:searchHits){
Long id = (Long) searchhit.getSource().get("id");
SearchResumeWithScore scoreResume = new SearchResumeWithScore();
scoreResume.setSearchResume(mapSearchResume.get(id));
// scoreResume.setScore(searchhit.getScore()) 会出现NaN异常
try{
float score = searchhit.getScore();
if(score > 0){
scoreResume.setScore(score);
}else{
scoreResume.setScore(0.0f);
}
}catch(Exception e){
scoreResume.setScore(0.0f);
}
scoreResumeList.add(scoreResume);
}
FacetedPageWithScore facetedPageWithScore = new FacetedPageWithScore(scoreResumeList, searchResult.getTotalPages());
return facetedPageWithScore;
}
});
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值