title: How to do script sort on nested field with Elasticsearch?
body: <p>I'm working with documents that looks like:</p>
  
  <pre><code>{
    "product_name": "abc",
    "prices": {
      "regular": 9.99,
      "pricing_tables": [
       { "id": 1, "price": 8.99 },
       { "id": 2, "price": 7.99 }
      ]
    }
  }
  </code></pre>
  
  <p>Where <em>prices.pricing_tables</em> is a nested field.</p>
  
  <p>What I want to do is sort with the following logic, given a pricing table id:</p>
  
  <ul>
  <li>If the nested field contains the given id, use pricing_tables.price</li>
  <li>If the nested field does not contain the id, use prices.regular</li>
  </ul>
  
  <p>The query I tried to use so far:</p>
  
  <pre><code>"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"
    }
  }  
  ]
  </code></pre>
  
  <p>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</p>
  
  <p>What am I missing here? Is it possible to do this?</p>