Метод компонента ‘elasticsearchTemplate’ не может быть найден в конфигурации

#java #spring #elasticsearch #querydsl

#java #весна #elasticsearch #querydsl

Вопрос:

Получение ошибки ниже:


НЕ УДАЛОСЬ ЗАПУСТИТЬ ПРИЛОЖЕНИЕ


Описание:

 Field template in com.rahul.es.api.service.QueryDSLService required a bean of type 'org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:
    - Bean method 'elasticsearchTemplate' in 'ElasticsearchDataConfiguration.RestClientConfiguration' not loaded because @ConditionalOnMissingBean (names: elasticsearchTemplate types: org.springframework.data.elasticsearch.core.ElasticsearchOperations; SearchStrategy: all) found beans of type 'org.springframework.data.elasticsearch.core.ElasticsearchOperations' elasticsearchTemplate and found beans named elasticsearchTemplate


Action:

Consider revisiting the entries above or defining a bean of type 'org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate' in your configuration.
  

EsConfig.java

 @Configuration(proxyBeanMethods=false)
@EnableElasticsearchRepositories(basePackages = "com.rahul.es.api.repository")
@ComponentScan(basePackages = { "com.rahul.es.api.service" })
public class EsConfig {

    @Bean
    public RestHighLevelClient client() {
        ClientConfiguration clientConfiguration 
            = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
 
        return RestClients.create(clientConfiguration).rest();
    }
 
    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(client());
    }
}
  

QueryDSLService

 @Service
public class QueryDSLService {

    @Autowired
    private ElasticsearchRestTemplate template;

    public List<Customer> searchMultipleField(String firstname, int age) {

        QueryBuilder query = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("firstname", firstname))
                .must(QueryBuilders.matchQuery("age", age));

        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
        List<Customer> customers = template.queryForList(nativeSearchQuery, Customer.class);
        return customers;
    }

    public List<Customer> getCustomerSearchData(String input) {
        String search = ".*"   input   ".*";
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withFilter(QueryBuilders.regexpQuery("firstname", search)).build();
        List<Customer> customers = template.queryForList(searchQuery, Customer.class);
        return customers;
    }

    public List<Customer> multiMatchQuery(String text) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.multiMatchQuery(text)
                .field("firstname").field("lastname").type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
        List<Customer> customers = template.queryForList(searchQuery, Customer.class);
        return customers;

    }

}
  

RestController

 @SpringBootApplication
@RestController
public class SpringbootElasticsearchQuerydslApplication {
    
    @Autowired
    private QueryDSLService service;

    @GetMapping("/serachMultiField/{firstname}/{age}")
    public List<Customer> serachByMultiField(@PathVariable String firstname, @PathVariable int age) {
        return service.searchMultipleField(firstname, age);
    }

    @GetMapping("/customSearch/{firstName}")
    public List<Customer> getCustomerByField(@PathVariable String firstName) {
        return service.getCustomerSearchData(firstName);
    }

    
    /**Based on wildcard method */
    @GetMapping("/search/{text}")
    public List<Customer> doMultimatchQuery(@PathVariable String text) {
        return service.multiMatchQuery(text);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootElasticsearchQuerydslApplication.class, args);
    }

}
  

Комментарии:

1. Вы получили решение?

Ответ №1:

Попробуйте добавить имя компонента, как указано в документах https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients

 @Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException {
    return new ElasticsearchTemplate(elasticsearchClient());
}
  

Ответ №2:

Вместо того, чтобы вводить компонент ElasticsearchOperations, вам необходимо ввести ElasticsearchRestTemplate, как четко указано в ошибке, и также изменить beanName с elasticsearchTemplate на elasticsearchRestTemplate .

     @Bean
    public ElasticsearchRestTemplate elasticsearchRestTemplate()
    {
        return new ElasticsearchRestTemplate(client());
    }
  

Примечание: я протестировал его на своей стороне, поскольку только что столкнулся с той же проблемой.