Spring Boot 2.7.x and Elasticsearch

It has been a long time since I did anything with Elasticsearch and I wanted to give it a go again. So I spun up a Spring Boot application through the Spring Initializr and downloaded the latest and greatest Elasticsearch, version 8.x.x.

I then could not get it to work and found that Spring Data Elasticsearch 4.4.5 only supports Elasticsearch 7.17.6. So I downloaded that and did the following.

I added the following to $ES_HOME/config/elasticsearch.yml:

xpack.security.enabled: true
discovery.type: single-node

We are running Elasticsearch as a single node. That is why I set the discovery.type.

Then I started Elasticsearch and setup passwords. If you don’t enable security, Elasticsearch logs a message every time you send a request to it, stating you’re doing unsafe things.

I set the passwords by executing:

$ES_HOME/bin/elasticsearch-setup-passwords auto

Elasticsearch then spits out the passwords for the various accounts. As I am only playing around with Elasticsearch and this is no a production setting, I am using the elastic account in Spring Boot.

What I did next was configure Elasticsearch in Spring Boot:

@Configuration
public class ElasticConfiguration extends AbstractElasticsearchConfiguration {

    @Override
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = 
            ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .withBasicAuth("elastic","<password>")
                .build();

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

Of course you would want put the username and password in a configuration file and not code, but we are just horsing around here.

Then it is just a matter of making a repository and a storage object and you are good to go:

public interface UserRepository extends ElasticsearchRepository<User, String> {
}

The User object looks like this:

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "user")
public class User {
    @Id
    private String id;
    private String username;
    private String department;
}

Leave a Reply

Your email address will not be published. Required fields are marked *