Search code examples
spring-bootelasticsearchspring-data-elasticsearch

How to make a custom converter for a String field using Spring Data Elasticsearch?


I am using Spring Data Elasticsearch in my project. I have a class like this,

@Document("example")
class Example {

@Id
private String id;
private String name;
private String game;
private String restField;
}

What I need is when ever I am saving the Example object to elasticsearch I am removing a value. But when I am getting the data from elasticsearch I need that removed value to be appended.

save(Example example) {
   example.setRestField(example.getRestField().replace("***", ""));
   exampleRepository.save(example);
}

get(String id) {
   Example example = exampleRepository.findById(id);
   example.getRestField().concat("***");
   return example;
}

Right now I am doing like the above way. But can we use a custom converter for this? I checked the converter examples for Spring Data Elasticsearch but those are for different different objects. How I can create a custom converter only for this particular String field restField? I don't want to apply this converter for other String fields.


Solution

  • Currently there is no better solution. The converters registered for Spring Data Elasticsearch convert from a class to a String and back. Registering a converter for your case would convert any String property of every entity.

    I had thought about custom converters for properties before, I have created a ticket for this.

    Edit 05.11.2021:

    Implemented with https://github.com/spring-projects/spring-data-elasticsearch/pull/1953 and will be available from 4.3.RC1 on.