Search code examples
c#sortingelasticsearchnestelasticsearch-5

NEST Elasticsearch advanced sorting


I have a lot of animal documents and I want to sort the items, that the cats should result first, the other animals afterwards.

My approach

var client = new Nest.ElasticClient(settings);
client.Search<Animals>(s => s.MatchAll().Sort(y => y.Descending(d => d.Type == "cat"))); 

But it doesn't give the desired result.


Solution

  • For this you need to use script sorting

    If you want the field in source with name type. You can't get a value of a text field but this will work for keyword field

       var items =  db.Search<Animals>(s => s.
                       Index("test").
                       Type("").
                       Sort(sort => sort.
                                    Script(sd => sd.
                                                 Type("number").
                                                 Script(sdd => sdd.
                                                               Inline("doc['type.keyword'].value == 'cat' ? 0 : 1")).
                                                               Ascending())));
    

    If you want the index type of the source. Note I would not recommend using this for new apps since they will remove this in ES6

    var items2 = db.Search<Animals>(s => s.
                    Index("test").
                    Type("").
                    Sort(sort => sort.
                                 Script(sd => sd.
                                              Type("number").
                                              Script(sdd => sdd.
                                                            Inline("doc['_type'].value == 'cat' ? 0 : 1")).
                                                            Ascending())));