Datetime 在elasticsearch上查询最接近日期时间的文档的最佳方式是什么?
我需要检索与请求具有最接近地理位置和日期时间的文档,因此我不是在寻找日期时间的匹配项,而是最接近的。我用一个自定义脚本解决了这个问题,不过我想可能有更好的方法,类似于我根据位置和距离过滤地理位置的方法 以下是我的代码(python): 自定义calculate-score.groovy脚本包含以下内容:Datetime 在elasticsearch上查询最接近日期时间的文档的最佳方式是什么?,datetime,groovy,
elasticsearch,Datetime,Groovy,
elasticsearch,我需要检索与请求具有最接近地理位置和日期时间的文档,因此我不是在寻找日期时间的匹配项,而是最接近的。我用一个自定义脚本解决了这个问题,不过我想可能有更好的方法,类似于我根据位置和距离过滤地理位置的方法 以下是我的代码(python): 自定义calculate-score.groovy脚本包含以下内容: abs(new java.text.SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm").parse(stamp).getTime() - doc["stamp"].
abs(new java.text.SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm").parse(stamp).getTime() - doc["stamp"].date.getMillis()) / 60000
脚本返回的分数是文档日期时间和请求日期时间之间的绝对差值(以分钟为单位)
有没有其他方法可以实现这一点?您应该可以使用。
您可以使用doucmentation中提到的衰减函数为更接近原始时间戳的文档提供更高的分数。下面是一个例子
其中刻度=28800分钟
即20d
例如:
put test
put test/test/_mapping
{
"properties": {
"stamp": {
"type": "date",
"format": "dateOptionalTime"
}
}
}
put test/test/1
{
"stamp":"2015-10-15T00:00"
}
put test/test/2
{
"stamp":"2015-10-15T12:00"
}
post test/_search
{
"query": {
"function_score": {
"functions": [
{
"linear": {
"stamp" : {
"origin": "now",
"scale": "28800m"
}
}
}
],
"score_mode" : "multiply",
"boost_mode": "multiply",
"query": {
"match_all": {}
}
}
}
}
谢谢这正是我想要的,它提供了相同的结果,而不需要定制脚本。在看了你的答案后,我搜索了线性函数,我偶然发现了这个,真不敢相信我错过了!链接到此功能的参考:
put test
put test/test/_mapping
{
"properties": {
"stamp": {
"type": "date",
"format": "dateOptionalTime"
}
}
}
put test/test/1
{
"stamp":"2015-10-15T00:00"
}
put test/test/2
{
"stamp":"2015-10-15T12:00"
}
post test/_search
{
"query": {
"function_score": {
"functions": [
{
"linear": {
"stamp" : {
"origin": "now",
"scale": "28800m"
}
}
}
],
"score_mode" : "multiply",
"boost_mode": "multiply",
"query": {
"match_all": {}
}
}
}
}