Elasticsearch JEST date serialization java

1.7k views Asked by At

I am using ES Jest. I can make a search and get the response. But when I do the serialization with the Date property, I got a null response after serialization.

The following is my class for ES document index and search result:

public class IndexDocument {
  public long id;
  @JsonSerialize(using = JsonDateSerializer.class)
  public Date Date1;
  @JsonSerialize(using = JsonDateSerializer.class)
  public Date Date2;
}

I have the following code for Date serialization:

public class JsonDateSerializer extends JsonSerializer<Date> {
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");
    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        String formattedDate = dateFormat.format(date);
        gen.writeString(formattedDate);
    }
}

Response from ES:

"hits" : [{
        "_index" : "myindex",
        "_type" : "mytype",
        "_id" : "3",
        "_score" : 1.3294203,
        "_source" : {
            "Date1" : "2016-11-24T14:39:08.000Z",
            "id" : 1,
            "Date2" : "1900-01-01T00:00:00.000Z"
        }
    }
]

My serialization code:

JestResult result = client.execute(search);   // i can see the response here 
response =  result.getSourceAsObjectList(IndexDocument.class);

After serialization, I get response = null

If I remove the date property from indexDocument, I can see the serialized response. However, with the date property, it is not working. What went wrong?

1

There are 1 answers

0
Alex On

JEST uses gson to parse dates, so your jackson annotation is not used when search result is parsed by jest. You might find this solution helpful: https://jtruty.github.io/programming/2015/04/03/elasticsearch-http-queries-with-jest.html