Search code examples
javaspring-dataspring-data-elasticsearch

Ignore property when persisting to ES, don't ignore when persisting to DB


Using spring-data(-elasticsearch), I want to persist a property to a PSQL DB but not to Elasticsearch, i.e. the opposite to this question: Spring data: How to ignore field for relational database but not in elasticsearch?

In other words:

  • when inserting this entity into ES, ignore myDate
  • when inserting this entity into a DB, persist myDate
@Entity
@Table("example")
@Document(indexName = "example")
public class Example implements Serializable {
  
  @Column(name = "my_date")
  @xyz
  private Instant myDate;

}

What should take the place of @xyz ? Is this possible at all?

  • @org.springframework.data.annotation.Transient excludes the property from both PSQL and ES
  • @JsonIgnore does nothing

Solution

  • Don't use the same entity for multiple Spring Data modules. As you notice, this is an accident waiting to happen.

    You could implement a BeforeConvertCallback (see the reference documentation) and set the myDate property to null, so it won't be sent to Elasticsearch.