1

I have a document which has a date field. I'd like to sort by documents by the this date ASC, but ones with a date in the past i'd like at the end.

In my end, it's like i want to assign the document value to a new value: - If date is > "utc now", then assign value to whatever the date is - If date is < "utc now", then assign value to max date

Then, i can sort by this field ASC.

So, it seems the only way to achieve this is with painless scripting.

This is what i've got so far, works.. but not sure if it's the correct approach.

GET /listings/_search
{
  "track_total_hits": true,
  "from": 0,
  "query": {
     "match_all": {}
  },
  "size": 48,
  "sort": [
    {
      "_script" : {
        "type": "string",
        "script": {
          "lang": "painless",
          "source": "if (doc['auctionOn.utc'].size() == 0) { return params['maxTimestamp'].toString(); } else { long timestampDoc = doc['auctionOn.utc'].value.toInstant().toEpochMilli();long timestampNow = new Date().getTime();if (timestampDoc > timestampNow) { return timestampDoc.toString(); } else { return params['maxTimestamp'].toString(); } }",
          "params": {
            "maxTimestamp": 9223372036854776000
          }
        },
        "order": "asc"
      }        
    }
  ]
}

can someone please advise if this is the correct/performant approach?

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Well, you could use function score. F1 querry date > now, and F2 querry date < now. Should be faster than a script. https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html – LeBigCat Jul 31 '19 at 12:35
  • @LeBigCat could you please put up an answer with what you're proposing? I read article but don't follow how it applies to me.. – RPM1984 Aug 01 '19 at 21:18
  • @LeBigCat also i'm now wondering - what if i just add a 'should' clause saying `auctionOn.utc > now`, then use the default sort? (e.g score?) wouldn't that work, and be even better than function score? – RPM1984 Aug 02 '19 at 06:20

0 Answers0