Search code examples
spring-boothibernate-search-6

Hibernate search 6 , refresh index after updating entity


I didn't find unfortunatly a solution for my Problem and I need help. I have tow entity like that

@Table(name = "A")
@Entity
@Indexed
@Getter
@Setter
@NoArgsConstructor
public class EntityA {

    @IndexedEmbedded
    @OneToOne(cascade = CascadeType.ALL)
    private EntityB b;
}


@Table(name = "B")
@Entity
@Indexed
@Getter
@Setter
@NoArgsConstructor
public class EntityB {

    @OneToOne(mappedBy = "b")
    private EntityA a;
    
    @KeywordField(name = "text_sort", sortable = Sortable.YES)
    @FullTextField(projectable = Projectable.YES)
    @Column(nullable = false)
    private String text;

}

I make a first save for my EntityA

EntityB entityB = new EntityB();
entityB.setText("text");
EntityA entityA = new EntityA();
entityA.setB(entityB);
entityARespository.save(entityA);

then I want to update the field text in the entityB, so I get first the entityA from the database and then make the update and save the entityA

EntityA entityA = entityARepository.findById(1L);
entityA.getB().setText("test")
entityBRepository.save(entityA); 

then when I make a research with the string "test" and don't find any result, but with string "text" yes . That's mean the index ist not refreshed but I didn't find where the problem is


Solution

  • Two possible explanations:

    1. Your update to the value test is done outside of a transaction. Make sure to use a transaction, or if you really don't want one, call entityManager.flush() (entityBRepository.flush() with Spring Data, I suppose?) after the call to save().

    2. You didn't wait long enough for the update to be visible. Elasticsearch is a near-real-time platform. This means your updates are not visible immediately, but after a periodic "refresh", which happens every second by default.

      See here for more information about the concept of "refresh".

      You can configure Hibernate Search to force a refresh after each index update by using the sync synchronization strategy, but then Elasticsearch's performance will be poor. I would only recommend that for automated tests, definitely not in production.