一尘不染

Spring SearchQuery ElasticSearch的每次点击得分

elasticsearch

在通过SearchQuery进行搜索时,我试图查看和使用每个匹配项的_score。除了别的以外,这还可以知道我的搜索在哪个分数范围内。但是除了使用searchQuery.withMinScore(float)设置MinScore之外;我找不到任何方法来处理搜索分数。

@Override
public Page<Website> listsearch(SearchBody searchBody, int size, int page) {
    BoolQueryBuilder qb = QueryBuilders.boolQuery();

    for(SearchUnit unit:searchBody.getSearchBody()){
        if(unit.isPriority()) {
            qb.must(matchQuery("_all", unit.getWord()).operator(MatchQueryBuilder.Operator.AND)
                    .fuzziness(Fuzziness.AUTO));

        }else {
            qb.should(termQuery("_all", unit.getWord())
                    .boost(unit.getWeight()));
        }
    }

    for(SearchUnit ExUnit:searchBody.getExcludeBody()){
        qb.mustNot(matchPhraseQuery("_all",ExUnit.getWord()));
    }

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withIndices("websites_v1")
            .withTypes("website")
            .withQuery(qb)
            .withMinScore(0.05F)//Magical minscore
            .withPageable(new PageRequest(page, size))
            .build();


    Page<Website> search = searchRepository.search(searchQuery);
    return search;

}

使用的搜索功能来自org.springframework.data.elasticsearch.repository; 定义为

Page<T> search(SearchQuery var1);

所以我的问题是无论如何我都可以访问页面中每个返回对象的分数?还是我需要将查询方法切换到其他方法才能实现?


阅读 427

收藏
2020-06-22

共1个答案

一尘不染

使用Spring Data ElasticSearch存储库是不可能的。

您需要自动连接an EntityMapper和an ElasticSearchTemplate并自己提取分数。这样的事情应该起作用:

Pageable pageRequest = new PageRequest(0, 10);
Page<Website> result = elasticSearchTemplate.query(searchQuery, new ResultsExtractor<Page<Website>>() {
    @Override
    public Page<Website> extract(SearchResponse response) {
        List<Website> content = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            Website website = entityMapper.mapToObject(hit, Website.class);
            content.add(website);
            float documentScore = hit.getScore(); // <---- score of a hit
        }
        return new PageImpl<Website>(content, pageRequest, response.getHits().getTotalHits());
    }
});
2020-06-22