30.6 Elasticsearch

Elasticsearch is an open source, distributed, real-time search and analytics engine. Spring Boot offers basic auto-configuration for the Elasticsearch and abstractions on top of it provided by Spring Data Elasticsearch. There is a spring-boot-starter-data-elasticsearch ‘Starter’ for collecting the dependencies in a convenient way. Spring Boot also supports Jest.

30.6.1 Connecting to Elasticsearch using Jest

If you have Jest on the classpath, you can inject an auto-configured JestClient targeting [localhost:9200](http://localhost:9200/) by default. You can further tune how the client is configured:

spring.elasticsearch.jest.uris=http://search.example.com:9200
spring.elasticsearch.jest.read-timeout=10000
spring.elasticsearch.jest.username=user
spring.elasticsearch.jest.password=secret

To take full control over the registration, define a JestClient bean.

30.6.2 Connecting to Elasticsearch using Spring Data

You can inject an auto-configured ElasticsearchTemplate or Elasticsearch Client instance as you would any other Spring Bean. By default the instance will embed a local in-memory server (a Node in Elasticsearch terms) and use the current working directory as the home directory for the server. In this setup, the first thing to do is to tell Elasticsearch where to store its files:

spring.data.elasticsearch.properties.path.home=/foo/bar

Alternatively, you can switch to a remote server (i.e. a TransportClient) by setting spring.data.elasticsearch.cluster-nodes to a comma-separated ‘host:port’ list.

spring.data.elasticsearch.cluster-nodes=localhost:9300
_@Component_
public class MyBean {

    private ElasticsearchTemplate template;

    _@Autowired_
    public MyBean(ElasticsearchTemplate template) {
        this.template = template;
    }

    // ...

}

If you add a @Bean of your own of type ElasticsearchTemplate it will replace the default.

30.6.3 Spring Data Elasticsearch repositories

Spring Data includes repository support for Elasticsearch. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.

In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common infrastructure; so you could take the JPA example from earlier and, assuming that City is now an Elasticsearch @Document class rather than a JPA @Entity, it will work in the same way.

[Tip] Tip
For complete details of Spring Data Elasticsearch, refer to their reference documentation.

results matching ""

    No results matching ""