Merging buckets after top_hits

Hi, I've a use case which I need help with. The mapping is as shown below of an elastic index:

{
   "test_case":{
      "type":"nested",
      "properties":{
         "end_timestamp":{
            "type":"date"
         },
         "pid":{
            "type":"integer"
         },
         "run_status":{
            "type":"keyword"
         },
         "start_timestamp":{
            "type":"date"
         }
      }
   },
   "test_info":{
      "properties":{
         "entity_type":{
            "type":"keyword"
         },
         "name":{
            "type":"keyword"
         },
         "pid":{
            "type":"integer"
         },
         "test_type":{
            "type":"keyword"
         }
      }
   }
}

Here each document can have same test_case repeated. Meaning doc1: has 3 testcases and doc2: has 5 testcases. But 2 testcases are common in them [common in pid].

The question is: Get the latest unique testcases from each document and then group them by test_info.test_type. This would be like find the latest document for each testcase based on test_case.start_timestamp and then group them into a fresh set of buckets based on test_info.test_type.

I'm open to any possible answer.