Sort by multiple fields

Does Nest support sorting across multiple fields? For example, let's say I want to sort by FieldA first, and then descending FieldB.

My current approach looks something like this:

searchDescriptor.Sort(s =>s.OnField("FieldA").Ascending().OnField("FieldB").Descending());

But the "FieldB" .Descending () part seems to be the only sort option that is sent to elasticsearch.

Does anyone know if there is another way to do this?

+4
source share
4 answers

You add multiple fields to the same sort descriptor that overrides the previous value. Instead, you need to specify a new sort descriptor for each field:

searchDescriptor
    .Sort(s => s
        .OnField("FieldA")
        .Ascending()
    )
    .Sort(s => s
        .OnField("FieldB")
        .Descending()
    )
+8
source

SortDescriptor.

        var sortDescriptor = new SortDescriptor<{YourType}>();

        sortDescriptor.Field(f => f.YourFieldName, Nest.SortOrder.Ascending);

        // If Field Name is Dynamic
        sortDescriptor.Field(
            "someOtherFieldName",
            Nest.SortOrder.Descending);         

        var searchResponse = await client.SearchAsync<{YourType}>(x => x
        .Query(y => query)
        .Sort(s => sortDescriptor)
        .From(from)
        .Size(size)
        );
+2

In the latest version of Nest, the correct way to sort by multiple files would be:

.Sort(s => s
    Field(f => f
        .Field("FieldA")
        .Order(SortOrder.Ascending)
    )
    .Field(f => f
        .Field("FieldB")
        .Order(SortOrder.Ascending)
    )
);
+2
source

You can use it like that. You can also use names from your model.

   EsClient.Search<Business>(s => s
      .Query (qq=> {...})
      .Sort(sort => sort.OnField(s => s.Name).Descending())
      .Sort(sort => sort.OnField(s => s.Age).Descending())
    )
0
source

All Articles