elasticsearchspring-data-elasticsearchresthighlevelclientfield-names

FieldNamingStrategy with Spring Data Elasticsearch


I'm configuring an elasticsearch spring application, and following the docs i've created this RestHighLevelClient:

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()  
            .connectedTo("localhost:9200")
            .build();

        return RestClients.create(clientConfiguration).rest();                         
    }
}

Now I want that all my Documents have as naming strategy the snake_case, and on the docs this is what i found:

Without further configuration, Spring Data Elasticsearch will use the property name of an object as field name in Elasticsearch. This can be changed for individual field by using the @Field annotation on that property.

It is also possible to define a FieldNamingStrategy in the configuration of the client (Elasticsearch Clients). If for example a SnakeCaseFieldNamingStrategy is configured, the property sampleProperty of the object would be mapped to sample_property in Elasticsearch. A FieldNamingStrategy applies to all entities; it can be overwritten by setting a specific name with @Field on a property.

The question is, how can I configure the client once for all?


Solution

  • just override the fieldNamingStrategy() method in your configuration class:

    @Configuration
    public class RestClientConfig extends AbstractElasticsearchConfiguration {
    
        @Override
        @Bean
        public RestHighLevelClient elasticsearchClient() {
    
            final ClientConfiguration clientConfiguration = ClientConfiguration.builder()  
                .connectedTo("localhost:9200")
                .build();
    
            return RestClients.create(clientConfiguration).rest();                         
        }
    
        @Override
        protected FieldNamingStrategy fieldNamingStrategy() {
            return new SnakeCaseFieldNamingStrategy();
        }
    
    }