# Sort ctx.payload using Transformed field

**URL:** <https://discuss.elastic.co/t/sort-ctx-payload-using-transformed-field/308869>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [July 5, 2022, 7:59am UTC](https://discuss.elastic.co/t/sort-ctx-payload-using-transformed-field/308869 "2022-07-05T07:59:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![M.Naim](https://avatars.discourse-cdn.com/v4/letter/m/54ee81/32.png) [@M.Naim](https://discuss.elastic.co/u/M.Naim)\
**Post date:** [July 5, 2022, 7:59am UTC](https://discuss.elastic.co/t/sort-ctx-payload-using-transformed-field/308869/1 "2022-07-05T07:59:03Z")

</div>

I want to sort the email content of watcher based on transformed field,consider "HoursDelayed": from example below Any Idea ?

```auto
    "send_email": {
      "transform": {
        "script": {
          "source": """
          long currdate = new Date().getTime();
          def documents = ctx.payload.aggregations.file_delay_agg.buckets.stream()
            .filter(fact -> (fact.key[2] =='Pyxis MedStation ES System' && (currdate - fact.extractionDateTime.value)/(1000 * 60 * 60) > fact.min_es_file_delay.value) ||
                (fact.key[2] =='EMR System' && (currdate - fact.extractionDateTime.value)/(1000 * 60 * 60) > fact.max_admin_file_delay.value))
            .map(hit -> [
              "key": hit.key_as_string,
              "idnName": hit.key[0],
              "facilityName": hit.key[1],
              "sourcesystem": hit.key[2],
              "clientKey": String.format('%.0f', new def[] { hit.key[3]}),
              "timeZone": hit.key[4],
              "HoursDelayed": String.format('%02d:%02d:%02d', new def[] {((currdate - hit.extractionDateTime.value)/(1000*60*60)).intValue(), ((((currdate - hit.extractionDateTime.value)/1000)% 3600) /60).intValue(), (((currdate - hit.extractionDateTime.value)/1000)% 60).intValue() }) ,
              "max_admin_file_delay": String.format('%.0f', new def[] { hit.max_admin_file_delay.value}),
              "min_es_file_delay": String.format('%.0f', new def[] { hit.min_es_file_delay.value}),
              "lastfiledate": hit.lastfiledate.value,
              "ExtractionDate": hit.lastfiledate.value_as_string,
              "max_date": hit.max_date.value_as_string,
              "min_date": hit.min_date.value_as_string
              ])    
            .collect(Collectors.toList());
          return documents; 
          """,
          "lang": "painless"
        }
      },

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [August 2, 2022, 7:59am UTC](https://discuss.elastic.co/t/sort-ctx-payload-using-transformed-field/308869/2 "2022-08-02T07:59:29Z")

</div>

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