我正在尝试通过SearchQuery进行搜索时查看并使用每个匹配的invidual _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);
所以我的问题是,无论如何我可以访问页面中每个返回对象的分数?或者我是否需要将查询方法切换为其他内容才能实现?
答案 0 :(得分:1)
Spring Data ElasticSearch存储库无法做到这一点。
您需要自动装配EntityMapper
和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());
}
});