John Doe John Doe - 4 months ago 23
Java Question

Java elasticsearch spring-data set different index field name

I'm using elasticsearch java-api in combination with spring-data and have a problem with indexing a document.
I want a different name for an indexed field. That means not the same as in the java code:

Domainobject:

@Document(indexName = "testindex", type = "message")
public class MessageObject {

@Id
private String unid;

@FieldNameInElasticIndex(value = "javaMessage") // I want anything like that
private String message;

private String secondMessage;

private String thirdMessage;

...

getters & setters

...

}


Interface:

public interface MessageObjectRepository extends ElasticsearchRepository<MessageObject, Long> {


}


Service:

@Component
public class MessageService {

@Autowired
private MessageObjectRepository repository;


public void addRegistrationObject(MessageObject msg) {

repository.save(msg);
}
}


So....

is it possible to change the name so the index would look like:

"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testindex",
"_type": "message",
"_id": "00113B325ED357B7C1257E2D001D5B4B",
"_score": 1,
"_source": {
"unid": "00113B325ED357B7C1257E2D001D5B4B",
"javaMessage": "Hello", // <--- this is what I want (javaMessage)
"secondMessage": null,
"thirdMessage": "Third",


instead of

"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testindex",
"_type": "message",
"_id": "00113B325ED357B7C1257E2D001D5B4B",
"_score": 1,
"_source": {
"unid": "00113B325ED357B7C1257E2D001D5B4B",
"message": "Hello", // <--- this is NOT what I want (java name: message)
"secondMessage": null,
"thirdMessage": "Third",


?

Val Val
Answer

The idea is simply to use the @JsonProperty annotation on the field and give the name you want to use during the JSON serialization:

@JsonProperty("javaMessage")
private String message;
Comments