Placing sorting on a document based on a particular nested document

Hi there,

I have documents of type "entity" containing nested document "users" of the format:

"users": {
  "type": "nested",
     "properties": {
       "id": {
         "type": "string",
         "index": "not_analyzed"
       },
       "timestamp": {
         "type": "long"
      },
      "status": {
         "type": "string",
         "index": "not_analyzed"
      }
   }
}

I want to sort my "entity" document based on the descending order of "timestamp" inside "users". I also need to filter out "users" based on status, only consider COMPLETED users. So, overall, my query is "Give me the latest 5 entity documents where latest is to be decided based on timestamp in the COMPLETED users".

I tried something like:

{
  "sort": {
    "users.timestamp": {
      "order": "desc",
      "nested_filter": {
        "term": {
          "users.status": "COMPLETED"
        }
      }
    }
  }
}

This works well when there is only one entry in users inside my entity document.
How do I ensure that while taking timestamp to decide on the sort order, I only take the user that has the latest timestamp?

Hi,

I think you also need to specify the nested_path and the sort mode parameter that decides which of the multi-valued "timestamps" in all the nested user documents you want to sort by. I tried this on a quick example (maybe not covering all the details you have in your docs and your main query):

"sort": {
    "users.timestamp": {
      "order": "desc",
      "mode":  "max",
      "nested_path" : "users",
      "nested_filter": {
        "term": {
          "users.status": "COMPLETE"
        }
      }
    }
  }

Thanks Christoph.

That worked like a charm.

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