Search code examples
c#sortingelasticsearch

In ElasticSearch how to apply complex Sorts when not using the Fluent Api on latest .NET client


I'm trying to work out how to build complex query and sorting scenarios. I am new to ElasticSearch. I'm building queries using "SearchRequest" object, NOT the FluentApi. I build my queries dynamically and they are working fine.

var request = new SearchRequest(indexName)
{
    From = from,    
    Size = size,
    Query = searchQuery
    // Sort = new List<SortOptions>() {  .. how do I create SortOptions ?? .. }
};
var response = await Client.SearchAsync<T>(request, cancellationToken);

The documentation shows how to use the fluent api, and other examples on stack overflow and so on show the same. There are examples for the non-fluent API on earlier versions of the client including NEST, but not for the latest 8.x

I need to generate SortOptions somehow. I found a static factory for SortOption.Field("field_name"), but no way to set ASC or DESC. I suspect the answer is in the descriptors, but unsure how. It seems that ALL the documentation around version 8+ is extremely poor compared to 7 and below with the NEST clients. Either that or I've missed a link to the reference docs.

I will want to sort on columns (asc and desc), and potentially on score (I noticed a Static factory method for this as well but was unsure how to create the parameter it needs.

All the core types are SEALED and cannot be instantiated directly. Appreciate all help. Thanks in advance.


Solution

  • Something like this would work. There may be a more succinct way but I cannot find it.

    Sort = new List<SortOptions>() { 
    SortOptions.Field("NameofField", new FieldSort() { Order= SortOrder.Asc})
    }```