Spring Data Elasticsearch findBy delay

20 views Asked by At

Looks like there is a delay between saving an entity and possibility to use findBy repository methods.

This is my code. Entity which is saved has @Id on sessionId field. The webSocketRepository.save() method is called right before this lines are executed.

 log.info("Total websockets: %d".formatted(webSocketRepository.findByDestination(destination).size()));
 var ws = webSocketRepository.findById(sessionId);
 if(ws.isPresent()) {
     log.info("Websocket exists: %s".formatted(ws.get().toString()));
 } else {
    log.info("Websocket not found with session id %s".formatted(sessionId));
 }
 log.info("Total websockets: %d".formatted(webSocketRepository.findByDestination(destination).size()));

and logs output:

[2024-02-28 18:22:33.211] INFO :61 - Total websockets: 0
[2024-02-28 18:22:33.231] INFO :64 - Websocket exists: *****
[2024-02-28 18:22:33.253] INFO :68 - Total websockets: 1

As you can see there is no elsaticsearch updates between first and second webSocketRepository.findByDestination calls, but result is different. I assume that it is because Elasticsearch should update some indexes in background and it takes some time.

Is any way in Spring Data Elasticsearch to wait until this indexes would be updated during repository.save() ?

1

There are 1 answers

0
P.J.Meisch On

That depends on the refresh policy of your server. With the default settings, Spring Data Elasticsearch does not set any parameter for that.

If you configure Spring Data Elasticsearch like described in the documentation, you can in your class that extends org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration overwrite the refreshPolicy() method. See the API docs for that method and possible values. The Elasticsearch documentation explains the different values.

If you are not using a repository, but an ElasticsearchOperations instance to save the data, you can change the refresh policy for a single call by using ElasticsearchOperations.withRefreshPolicy(refreshPolicy)