这是我在elasticsearch中的文档之一:
{
"_index": "2017-10-21",
"_type": "cat",
"_id": "14",
"_score": 2.2335923,
"_source": {
"name": "Biscuit",
"breed": "Persian",
"age": "3",
"purchase_date": "2017-11-11T10:16:18+0100",
"birth_date": "2017-01-21T10:16:18+0100"
}
}
我想计算“购买日期”和“出生日期”之间的时间(通过减去它们),例如以分钟或天为单位,并在这个时间添加一个新字段“age_when_bought”(在每个品种为“波斯语”的文档中) ”,但这不是重点)。应该是这样的:
POST /*/_update_by_query
{
"script" : {
"inline": "ctx._source.age_when_bought = ctx._source.purchase_date - ctx._source.birth_date"
},
"query": {
"bool": {
"must": [
{
"match": {
"breed": "Persian"
}
}
]
}
}
}
不幸的是,它不能以这种方式工作。我的响应出现错误 500:
"caused_by": {
"type": "class_cast_exception",
"reason": "Cannot apply [-] operation to types [java.lang.String] and [java.lang.String]."
}
我已经尝试过将这些字段转换为日期,但我可能不会使用好的函数来做到这一点:
'SimpleDateFormat.parse(ctx._source.purchase_date)'
这次我的响应仍然出现错误 500:
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Unknown call [parse] with [1] arguments on type [SimpleDateFormat]."
}
感谢您的帮助!
最佳答案
我终于找到解决办法了!
POST /*/_update_by_query
{
"script" : {
"inline": "ctx._source.age_when_bought = (new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:sszzz\").parse(ctx._source.purchase_date).getTime()
- new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:sszzz\").parse(ctx._source.birth_date).getTime())"
},
"query": {
"bool": {
"must": [
{
"match": {
"breed": "Persian"
}
}
]
}
}
}
SimpleDateFormat 是一个以区域设置敏感的方式格式化和解析日期的类。它允许格式化(日期 -> 文本)、解析(文本 -> 日期)和标准化。
Date.getTime() 方法返回自 1970 年 1 月 1 日 00:00:00 GMT 以来过去了多少毫秒。
因此,通过执行 date_1.getTime() - date_2.getTime()
,结果将是 date_1 和 date_2 之间的时间(以毫秒为单位)(假设 date_1 比当前日期更接近) date_2。否则,结果可能相同但为负)。
关于java - ElasticSearch:脚本内联减去日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47432662/