# Using scripted nested sorting with missing fields

**URL:** <https://discuss.elastic.co/t/using-scripted-nested-sorting-with-missing-fields/226962>\
**Category:** Elasticsearch\
**Created:** [April 7, 2020, 5:24pm UTC](https://discuss.elastic.co/t/using-scripted-nested-sorting-with-missing-fields/226962 "2020-04-07T17:24:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jimmy](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jimmy/32/55277_2.png) [@Jimmy](https://discuss.elastic.co/u/Jimmy)\
**Post date:** [April 7, 2020, 5:24pm UTC](https://discuss.elastic.co/t/using-scripted-nested-sorting-with-missing-fields/226962/1 "2020-04-07T17:24:43Z")

</div>

Hi,

I'm working with documents that looks like:

```
{
  "product_name": "abc",
  "prices": {
    "regular": 9.99,
    "pricing_tables": [
     { "id": 1, "price": 8.99 },
     { "id": 2, "price": 7.99 }
    ]
  }

```

Where _prices.pricing\_tables_ is a nested field.

What I want to do is sort with the following logic, given a pricing table id:

- If the nested field contains the given id, use pricing\_tables.price

- If the nested field does not contain the id, use prices.regular

The query I tried to use so far:

```
"sort": [
{
  "_script": {
    "type": "number",
    "script": {
      "lang": "painless",
      "source": """
        if(doc['prices.pricing_tables.price'].size() != 0) { 
          return doc['prices.pricing_tables.price'].value; 
        } 
        else {
          return doc['prices.regular'].value;
        }
        """
    },
    "nested": {
      "path": "prices.pricing_tables",
      "filter": {
        "term": {"prices.pricing_tables.id": 1}
      }
    },
    "order": "asc"
  }
}  
]

```

However it does not work as expected. When there is no entries in the pricing\_tables nested object, the sort value in the result is always 1.7976931348623157E308

What am I missing here? Is it possible to do this?

Thanks!

---

<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:** [May 5, 2020, 5:24pm UTC](https://discuss.elastic.co/t/using-scripted-nested-sorting-with-missing-fields/226962/2 "2020-05-05T17:24:46Z")

</div>

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