Sorting Elasticsearch based on multiple fields and time
I have a small app for an online store and I would like to sort products by their active price. So there is a normal price and possibly a discounted price. But the discounted price is only valid for the time range and the index is not updated when the discount ends. For example:
{price: 2.00, discount:{price:1.10, start:2016-08-11, end:2016-09-14}}
Can such a condition be included in the sort? The goal is to ensure that the sort order is correct at all times.
Edit: The ES version is quite old at the moment, but updating to the latest is not a problem.
source to share
This is for Elasticsearch 5 and 6 (you didn't mention, as I said, the version and display of this field discount
). In addition, you must explicitly pass the current date and time in milliseconds as a parameter whenever you run this request:
"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"
}
}
source to share