基于this answer和注释,我实现了接收弹性搜索查询分数的代码。
public class CustomizedHotelRepositoryImpl implements CustomizedHotelRepository {
private final ElasticsearchTemplate elasticsearchTemplate;
@Autowired
public CustomizedHotelRepositoryImpl(ElasticsearchTemplate elasticsearchTemplate) {
super();
this.elasticsearchTemplate = elasticsearchTemplate;
}
@Override
public Page<Hotel> findHotelsAndScoreByName(String name) {
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.should(QueryBuilders.queryStringQuery(name).lenient(true).defaultOperator(Operator.OR).field("name"));
NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder)
.withPageable(PageRequest.of(0, 100)).build();
DefaultEntityMapper mapper = new DefaultEntityMapper();
ResultsExtractor<Page<Hotel>> rs = new ResultsExtractor<Page<Hotel>>() {
@Override
public Page<Hotel> extract(SearchResponse response) {
ArrayList<Hotel> hotels = new ArrayList<>();
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
try {
Hotel hotel = mapper.mapToObject(hit.getSourceAsString(), Hotel.class);
hotel.setScore(hit.getScore());
hotels.add(hotel);
} catch (IOException e) {
e.printStackTrace();
}
}
return new PageImpl<>(hotels, PageRequest.of(0, 100), response.getHits().getTotalHits());
}
};
return elasticsearchTemplate.query(nativeSearchQuery, rs);
}
}正如您所看到的,我需要创建一个新的DefaultEntityMapper mapper = new DefaultEntityMapper();实例,但事实并非如此,因为它应该可以@Autowire EntityMapper。如果我这样做,我得到的异常是没有bean。
Description:
Field entityMapper in com.example.elasticsearch5.es.cluster.repository.impl.CustomizedCluserRepositoryImpl required a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' in your configuration.那么,有没有人知道是否可以直接自动布线bean,或者是否需要使用@Bean注释手动创建EntityMapper。
我在core包所在的位置使用spring-data-elasticsearch-3.0.2.RELEASE.jar。
我的pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>发布于 2018-02-21 23:26:30
我查看了spring-data-elasticsearch的source code。没有针对EntityMapper的bean/组件定义。看起来这个answer是错的。我在我的项目上测试了它,得到了同样的错误。
Consider defining a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' in your configuration.除了定义@Bean之外,我找不到任何其他选项
https://stackoverflow.com/questions/48830308
复制相似问题