2016-10-13 208 views
1

是否可以將日期字段與current time進行比較,然後根據比較結果進行排序(類似SQL順序中的開關情況)?Elasticsearch:按計算日期值排序

目標是使文檔具有一個特定的日期時間字段,其值大於當前時間,移動到列表的頂部,但具有小於當前時間的特定日期時間字段的所有文檔在優先級上相等不按此日期時間字段排序。

回答

1

首先,你可以使用microtime來簡單的使用。 Elasticsearch中有script sort功能。你也可以在這個腳本中使用if語句。

{ 
    "query" : { 
     .... 
    }, 
    "sort" : { 
     "_script" : { 
      "type" : "number", 
      "script" : { 
       "inline": "if (doc['time'].value > current_time) return doc['field_name'].value; else return current_time", 
       "params" : { 
        "current_time" : 1476354035 
       } 
      }, 
      "order" : "asc" 
     } 
    } 
} 

當您使用腳本運行查詢時,應發送當前時間。