# Sorting by max value of property of nested object array

**URL:** <https://discuss.elastic.co/t/sorting-by-max-value-of-property-of-nested-object-array/333778>\
**Category:** Elasticsearch\
**Created:** [May 18, 2023, 2:52pm UTC](https://discuss.elastic.co/t/sorting-by-max-value-of-property-of-nested-object-array/333778 "2023-05-18T14:52:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ndtreviv](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ndtreviv/32/22494_2.png) [@ndtreviv](https://discuss.elastic.co/u/ndtreviv)\
**Post date:** [May 18, 2023, 2:52pm UTC](https://discuss.elastic.co/t/sorting-by-max-value-of-property-of-nested-object-array/333778/1 "2023-05-18T14:52:20Z")

</div>

I have the following object model:

```auto
{
    ...
    "classification": [
        { "label": "aaa", "probability": 0.9923 },
        { "label": "bbb", "probability": 0.3452 },
        { "label": "ccc", "probability": 0.0012 },
   ]
}

```

I want to sort documents based on the label that has the highest probability value.

ie: Identify the label value of the nested object with the highest probability and sort on that.

I've tried this:

```auto
  "sort": {
    "classification.probability": {
      "mode": "max",
      "order": "desc",
      "missing": "_last",
      "nested": {
        "path": "classification"
      }
    }
  }

```

But it doesn't seem to be working - it seems to be sorting on the max probability value instead of the label of the object with the max probability value.

Is what I want even possible?

---

<div class="post-metadata">

**Author:** ![ndtreviv](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ndtreviv/32/22494_2.png) [@ndtreviv](https://discuss.elastic.co/u/ndtreviv)\
**Post date:** [May 18, 2023, 5:20pm UTC](https://discuss.elastic.co/t/sorting-by-max-value-of-property-of-nested-object-array/333778/2 "2023-05-18T17:20:01Z")

</div>

This is the solution:

```auto
  "sort": {
    "_script": {
      "type": "string",
      "script": {
        "lang": "painless",
        "source": "params._source['classification'] == null ? '' : params._source['classification'].stream().max((a, b) -> Double.compare(a.probability, b.probability)).get().label;"
      },
      "order": "asc"
    }
  }

```

---

<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:** [June 15, 2023, 5:20pm UTC](https://discuss.elastic.co/t/sorting-by-max-value-of-property-of-nested-object-array/333778/3 "2023-06-15T17:20:18Z")

</div>

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