Stale read in Elasticsearch using Spring Data

55 Views Asked by At

In my test case below, a Car is deleted.

Although the car is deleted, the test fails. According to the test, the car still exists. When I debug through the code, the test succeeds. This got me think about a stale read. Maybe the car is not removed yet in the Elasticsearch Container? I tried a Thread.sleep(3000) between the removal and read operations, even then the test keeps failing.

For information: all other read related tests succeed.

Test class using Elasticsearch Testcontainer:

@ContextConfiguration(classes = {
        ElasticsearchTestSliceConfiguration.class,
        CarElasticsearchRepository.class,
        CarElasticsearchRepository.CarElasticsearchSpringRepository.class})
@DataElasticsearchTest
class CarElasticsearchRepositoryIT extends ElasticsearchContainerTest {
  
  ...

  @Test
  void shouldRemoveCarById() {
    repository.remove(carId_001);
    final Optional<Car> car = repository.findBy(carId_001);

    assertThat(car).isEmpty();
  }

}

Repository implementation:

@Component
class CarElasticsearchRepository {

  private final CarElasticsearchSpringRepository springRepository;
 
  CarElasticsearchRepository (CarElasticsearchSpringRepository springRepository) {
    this.springRepository = springRepository;
  }

  public Optional<Car> findBy(CarId carId) {
    return springRepository.findCarDocumentByCarId(carId.getValue())
           .map(carDocument -> carDocument.toCar())
  }

  public void remove(CarId carId) {
    springRepository.findCarDocumentByCarId(carId.getValue())
                    .ifPresent(carDocument -> springRepository.deleteCarDocumentByCarId(carId.getValue()))
  }

  interface CarElasticsearchSpringRepository extends ElasticsearchRepository<CarDocument, String> {
    Optional<Car> findCarDocumentByCarId(String carId);
    void deleteCarDocumentByCarId(String carId);
  }

}

Used Java & lib versions:

  • Java 17
  • spring-data-elasticsearch 5.1.5
  • org.testcontainers 1.18.3
0

There are 0 best solutions below