2017-06-13 79 views
3

我有一個小的在線商店應用程序,我想根據它們的活動價格對商品進行排序。所以有一個正常的價格和可選的折扣價格。但折扣價格僅在一個時間範圍內有效,折扣結束時索引不會更新。例如:基於多個領域和時間條件的Elasticsearch排序

{price: 2.00, discount:{price:1.10, start:2016-08-11, end:2016-09-14}} 

是否有可能在排序中包含這樣的條件?目標是在任何給定時間確保正確的排序順序。

編輯:目前ES版本相當老,但更新到最新不是問題。

+0

可以使用_script做到這一點,基本上,你將不得不自己編寫一個腳本與排序將操作。我無法幫助您製作腳本請求,因爲我從未使用_script選項,所以我不會將其作爲答案發布,但您可以在此處找到更多信息: [基於腳本的排序](https:// www.elastic.co/guide/en/elasticsearch/reference/6.0/search-request-sort.html) – AlwaysGoingToAsk

+0

您在帖子中沒有提供太多信息:「discount」字段,ES版本的映射是什麼? –

回答

2

這是針對Elasticsearch 5和6(你沒有提到,如我所說的那個版本和那個discount字段的映射)。另外,你需要,只要你運行該查詢明確作爲參數傳遞以毫秒爲單位的當前日期和時間:

"sort": { 
    "_script": { 
     "type": "number", 
     "script": { 
     "lang": "painless", 
     "source": "if (doc['discount.price']!=null && doc['discount.start'].date.getMillis() < params['time'] && doc['discount.end'].date.getMillis() > params['time']) return doc['discount.price'].value; else return doc['price'].value", 
     "params": { 
      "time": 1512717897000 
     } 
     }, 
     "order": "desc" 
    } 
    } 
+2

只是一個OP的說明:在ES 6中,它警告:#!棄用:日期字段中不再需要getDate,因爲該值現在是日期。您可以使用:'doc ['discount.start'] .value.getMillis()'而不是'doc ['discount.start']。date.getMillis()'。 –

+0

有趣。我不知道@ArchitSaxena。感謝您添加此評論。 –