title: Script-based sorting on Elasticsearch date field
body: <p>I am just getting started with Elasticsearch and would like to use script-based sorting on a field that is mapped as <code>date</code>, format <code>hour_minute</code>. There can be multiple instances of the field in each document.</p>
  
  <p>Before introducing expressions, as a first step I'm trying a simple sort (using the Sense plugin):</p>
  
  <pre><code>POST myIndex/_search
  {
     "query": {
        "match_all": {}
     },
     "sort": {
        "_script": {
           "script": "doc[\"someTime\"].value",
           "lang": "groovy",
           "type": "date",
           "order": "asc"
        }
     }
  }
  </code></pre>
  
  <p>I get this error (fragment):</p>
  
  <pre><code>SearchPhaseExecutionException[Failed to execute phase [query], all shards failed;
  shardFailures {[tjWL-zV5QXmGjNlXzLvrzw][myIndex][0]:
  SearchParseException[[myIndex][0]: 
  query[ConstantScore(*:*)],from[-1],size[-1]: Parse Failure [Failed to parse source…
  </code></pre>
  
  <p>If I post the above query with <code>"type": "number"</code> there is no error, although this of course doesn't sort by date. The following works fine:</p>
  
  <pre><code>POST myIndex/_search
  {
     "query": {
        "match_all": {}
     },
     "sort": {
        "someTime": {
           "order": "asc"
        }
     }
  }
  </code></pre>
  
  <p>Ultimately I'd like to use script-based sorting since I will be trying to query, filter or sort using date and time conditions, like query for documents with today’s date, then sort them by the lowest time that is after the time now, etc.</p>
  
  <p>Any suggestions would be much appreciated.</p>