我刚看了一下,现有方法Page<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable)早在2013年就被添加到ElasticsearchRepository接口中,它只是返回一个Page<T>,其中不包含任何分数信息。
从 Spring Data Elasticsearch 4.0 版开始,分数信息可用,当您查看实现时,您会发现它已从函数的返回值中剥离,以便遵守接口中的方法签名:
public Page<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable) {
Assert.notNull(entity, "Cannot search similar records for 'null'.");
Assert.notNull(pageable, "'pageable' cannot be 'null'");
MoreLikeThisQuery query = new MoreLikeThisQuery();
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setPageable(pageable);
if (fields != null) {
query.addFields(fields);
}
SearchHits<T> searchHits = execute(operations -> operations.search(query, entityClass, getIndexCoordinates()));
SearchPage<T> searchPage = SearchHitSupport.searchPageFor(searchHits, pageable);
return (Page<T>) SearchHitSupport.unwrapSearchHits(searchPage);
}
您可以实现一个自定义存储库片段(请参阅https://docs.spring.io/spring-data/elasticsearch/docs/4.2.6/reference/html/#repositories.custom-implementations),该片段提供它自己的方法实现,该方法返回一个SearchPage<T>:
public SearchPage<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable) {
Assert.notNull(entity, "Cannot search similar records for 'null'.");
Assert.notNull(pageable, "'pageable' cannot be 'null'");
MoreLikeThisQuery query = new MoreLikeThisQuery();
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setPageable(pageable);
if (fields != null) {
query.addFields(fields);
}
SearchHits<T> searchHits = execute(operations -> operations.search(query, entityClass, getIndexCoordinates()));
SearchPage<T> searchPage = SearchHitSupport.searchPageFor(searchHits, pageable);
return searchPage;
}
SearchPage<T> 是一个包含SearchHit<T> 实例的页面;这些包含实体和分数等附加信息。