Elasticsearch Client returns timestamp as string

Viewed 467

I want to fetch some logs data from elasticsearch and return it to the UI using graphql. I am using the nestjs/elasticsearch client in my nest.js backend which is a wrapper of 'elastic/elasticsearch'. I have also mapped the timestamp field in the elasticsearch index as 'date'.

"mappings": {
    "properties": {
        "timestamp": {
            "type": "date"
        },
        "message": {
            "type": "keyword"
        },
    }
}

I have created the @ObjectType class as follows:

@ObjectType()
export class LogMessage {

  @Field()
  message: string;

  @Field()
  timestamp: Date;
   
}

But, while getting the documents from Elasticsearch, the timestamp is getting returned as a 'string'. And because the ObjectType expects 'timestamp' to be a Date, I get 'null' on the 'graphql' response for the 'timestamp' field. Changing to 'timestamp: string', I see the timestamp in the response.

How do I debug this issue and make sure that elasticsearch client returns the 'timestamp' as a 'Date'? Or Is this expected behavior and I need to convert the string to Date type manually?

1 Answers

It is expected behavior as ElasticSearch render date as a String. So as you mentioned, you need to convert string to date type. Please check this Date Field documentation of elasticsearch.

Below is snippet from doc:

JSON doesn’t have a date data type, so dates in Elasticsearch can either be:

  • strings containing formatted dates, e.g. "2015-01-01" or "2015/01/01 12:10:30".
  • a number representing milliseconds-since-the-epoch.
  • a number representing seconds-since-the-epoch (configuration).

Also from the same doc:

Dates will always be rendered as strings, even if they were initially supplied as a long in the JSON document.

Related