小编典典

Spring-Boot Elasticseach EntityMapper无法自动连线

spring-boot

基于此答案和评论,我实现了代码以接收elasticsearch查询的分数。

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 =newDefaultEntityMapper();但事实并非如此,因为应该可以@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.

因此,有人知道是否可以直接自动连接EntityMapper还是需要使用@Bean注释手动创建Bean 。

我用spring-data-elasticsearch-3.0.2.RELEASE.jarcore包里面。

我的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>

阅读 1155

收藏
2020-05-30

共1个答案

小编典典

我检查了spring-data-elasticsearch 的源代码。没有的bean
/组件定义EntityMapper。我在我的项目上对其进行测试,并得到相同的错误。

Consider defining a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' in your configuration.

除了定义@Bean,我找不到其他任何选择

2020-05-30