Sorting search results into buckets, and then sorting again

Hello,

I am trying to figure out a way to assemble a query to perform two levels of sorting. My documents have two fields that I'm trying to sort on:

{
   "user": {
          "type": "keyword"
    },
   "date": {
          "type": "long"
    },
}

I would like my search results to be returned in such a way that all documents with the same user field are adjacent to one another. So in a UI all the documents pertaining to one user show consecutively. Furthermore, I want to sort these buckets of user-aggregated documents according to the date timestamp, so that the bucket with the oldest date value shows up on the top of the search results.

I've been able to achieve this using an aggregation as follows:

{
   "size":0,
   "aggs":{
      "by_user":{
         "terms":{
            "field":"user",
            "order":{
               "oldest_date":"asc"
            }
         },
         "aggs":{
            "by_date":{
               "top_hits":{
                  "sort":[
                     {
                        "date":{
                           "order":"asc"
                        }
                     }
                  ]
               }
            },
            "oldest_date":{
               "min":{
                  "script":{
                     "inline":"doc['date'].value",
                     "lang":"painless"
                  }
               }
            }
         }
      }
   }
}

This works great, but the problem is I also need true pagination. Is there any way I can do this form of hierarchical sorting using just the sort option in my query so I can still use the pagination features?

Thanks in advance for the help!

Does anyone have some ideas on this?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.