Elasticsearch 客户端 returns 时间戳作为字符串
Elasticsearch Client returns timestamp as string
我想使用 graphql 从 elasticsearch 获取一些日志数据并 return 到 UI。
我正在使用 nestjs/elasticsearch client in my nest.js backend which is a wrapper of 'elastic/elasticsearch'。
我还将 elasticsearch 索引中的时间戳字段映射为 'date'.
"mappings": {
"properties": {
"timestamp": {
"type": "date"
},
"message": {
"type": "keyword"
},
}
}
我创建了 @ObjectType class 如下:
@ObjectType()
export class LogMessage {
@Field()
message: string;
@Field()
timestamp: Date;
}
但是,在从 Elasticsearch 获取文档时,时间戳被 return 编辑为 'string'。
因为 ObjectType
期望 'timestamp' 是一个日期,所以我在 'timestamp' 字段的 'graphql' 响应中得到 'null'。
更改为 'timestamp: string',我在响应中看到了时间戳。
如何调试此问题并确保 elasticsearch 客户端 return 将 'timestamp' 作为 'Date'?
或者
这是预期的行为吗,我需要手动将字符串转换为 Date 类型?
这是预期的行为,因为 ElasticSearch 将日期呈现为字符串。因此,正如您提到的,您需要将字符串转换为日期类型。
请检查elasticsearch的这个Date Field documentation。
下面是来自文档的片段:
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).
也来自同一文档:
Dates will always be rendered as strings, even if they were initially
supplied as a long in the JSON document.
我想使用 graphql 从 elasticsearch 获取一些日志数据并 return 到 UI。 我正在使用 nestjs/elasticsearch client in my nest.js backend which is a wrapper of 'elastic/elasticsearch'。 我还将 elasticsearch 索引中的时间戳字段映射为 'date'.
"mappings": {
"properties": {
"timestamp": {
"type": "date"
},
"message": {
"type": "keyword"
},
}
}
我创建了 @ObjectType class 如下:
@ObjectType()
export class LogMessage {
@Field()
message: string;
@Field()
timestamp: Date;
}
但是,在从 Elasticsearch 获取文档时,时间戳被 return 编辑为 'string'。
因为 ObjectType
期望 'timestamp' 是一个日期,所以我在 'timestamp' 字段的 'graphql' 响应中得到 'null'。
更改为 'timestamp: string',我在响应中看到了时间戳。
如何调试此问题并确保 elasticsearch 客户端 return 将 'timestamp' 作为 'Date'? 或者 这是预期的行为吗,我需要手动将字符串转换为 Date 类型?
这是预期的行为,因为 ElasticSearch 将日期呈现为字符串。因此,正如您提到的,您需要将字符串转换为日期类型。 请检查elasticsearch的这个Date Field documentation。
下面是来自文档的片段:
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).
也来自同一文档:
Dates will always be rendered as strings, even if they were initially supplied as a long in the JSON document.