Skip to content
Advertisement

Elasticsearch Sort based on value first

I want to sort results on the release date. I want 2015 movies first and the rest of the years sorted on the has_poster value. So I get results like:

2015, 2015, 1989, 2017, 2006

etc.

So far this is what I’ve got.

$params['index'] = 'movies';
$params['type']  = 'movie';
$params['body']['size'] = 50;
$params['body']['sort'] = array(
    array('has_poster'  => "desc"),
    array('_score'  => "desc"),
);        
$params['body']['query']['filtered'] = array(
    'query' => array(
        'query_string' => array(
            'query' => "survivor",
            'fields' => array('name', 'orig_title'),
            'default_operator' => "AND"
        ),
    )
);

I need the equivalent of ... ORDER BY FIELD(releasedate, 2015), has_poster DESC ... in MySQL for Elasticsearch.

Advertisement

Answer

You need a scripted sorting:

{
  "sort": [
    {
      "_script": {
        "script": "if(doc['releasedate'].date.year==2015) return 1; else return 0;",
        "type": "number",
        "order": "desc"
      }
    },
    {
      "has_poster": "desc"
    }
  ]
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement