0

I want to retrieve the last 3 documents from a set, taking into account that the desired elements order is given by a field named created. To do that I'm exploiting the combination of sort + order mechanism, as also pointed out in many SO Q&A:

Note: The field created in my case is a timestamp but wrapped on a long.

{
    "size" : 3,
    "sort": [
    {
      "created": {
        "order": "desc"
      }
    }
  ]
}

But with this stratagem the results are retrieved in descending order. I'd like them to be returned in ascending order. Which way may I combine these two requirements?

Example, having this set (in the form field:value;):

doc:A; created:1;
doc:C; created:2;
doc:F; created:3;
doc:D; created:4;
doc:B; created:5;
doc:H; created:6;
doc:G; created:7;

I want to retrieve the last three documents according to created, which is OK using the above query, but the results are given in in the order G, H, B corresponding to the value 7, 6, 5, while I would like to keep the order B, H, G, corresponding to the values 5, 6, 7 of the field created.

donnadulcinea
  • 1,854
  • 2
  • 25
  • 37
  • To change the order it's enough to change the value { "created": { "order": "asc" } . – Lupanoide Mar 07 '19 at 11:14
  • 1
    He wont have the 3 last created doc if he do that...He would have the older ones. – LeBigCat Mar 07 '19 at 14:46
  • You can handle this at application side. Loop through the `hits` array in reverse order. – Nishant Mar 07 '19 at 15:37
  • @NishantSaini Right now I'm handling this programmatically. So, it seems like the answer is that this is not possible just relying on ElasticSearch. – donnadulcinea Mar 08 '19 at 03:21
  • What you are trying to achieve is `order result -> limit result (size) -> reorder limited result`. This is not possible via elastic. – Nishant Mar 08 '19 at 07:33

0 Answers0