在弹性搜索中,文档包含参数validTo(时间戳(。考虑到价值,我想计算一下文件状态;如果validTo小于当前时间,则状态应为"已过期",否则,状态应该为"活动"。
以下是脚本请求示例(缺少状态计算部分(:
curl -X GET "localhost:9200/my_index/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"userId": "1"
}
},
"script_fields": {
"validTo": {
"script": {
"lang": "painless",
"source": "doc[u0027validTou0027].value" <-- example doc['validTo'] = "2019-01-05T10:17:35.000Z"
}
},
"status": {
"script": {
"lang": "painless",
// here the status should be calculated depending on the time condition
}
}
}
}
'
如果有任何帮助,我将不胜感激。
看,我尽了最大努力来解决这个问题,但最终我要在脚本源中获得当前的ZonedDateTime
,我面临着很多困难;
我知道它看起来很傻,但只要你不在乎时区,它就可以正常工作。
{
"script_fields": {
"status": {
"script": {
"lang": "painless",
"source": """
// get current date as string
String now = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
// add default timeZoned as string to be accepted in ZonedDateTime
now += ".000Z";
// get field value as string
String fieldDate = doc['Order Date'].value.toString();
// convert both; fieldDate and today into zdt
ZonedDateTime fieldZDT = ZonedDateTime.parse(fieldDate);
ZonedDateTime nowZDT = ZonedDateTime.parse(now);
// make comparsion
return fieldZDT.isBefore(nowZDT)? "expired": "active";
"""
}
}
}
}
我试过了,它对我有效。
我用以下脚本计算了状态:
"script_fields": {
"status": {
"script": {
"lang": "painless",
"source": """
long now = new Date().getTime();
String fieldDate = doc["validTo"].value.toString();
ZonedDateTime fieldZDT = ZonedDateTime.parse(fieldDate);
long nowZDT = new Date().getTime();
String nowString = params['now'];
long validToLong = doc["validTo"].value.toInstant().toEpochMilli();
long timeDiff = validToLong - now;
String status = timeDiff > 0 ? "VALID" : "EXPIRED";
status
"""
}
}
}