TBA
TBA

Reputation: 1187

NEST c# Query Creating SORT in Foreach - ElasticSearch

I have the following code to construct a SORT query inside a foreach loop, however my problem is this will replace my old sort descriptor with latest one.

SearchDescriptor<MyDTO> nQuery = new SearchDescriptor<MyDTO>();
foreach (var sort in criteria.SortQuery.OrderBy(o => o.SortPreference))
                {
                  nQuery=  nQuery.Sort(s => s.Field(sort.SortName, sort.SortOrder));
                }

How to achieve this inside a ForEach

Upvotes: 0

Views: 1943

Answers (1)

Rob
Rob

Reputation: 9979

You can do this by

var sortDescriptor = new SortDescriptor<Document>();

foreach (var sort in sortCollection)
{
    SortOrder sortOrder;
    var tryParse = Enum.TryParse(sort.Order, out sortOrder);
    if(!tryParse) up to you how you are going to handle incorrect sort order
    sortDescriptor.Field(sort.FieldName, sortOrder);
}

client.Search<Document>(s => s.Size(0).Sort(sort => sortDescriptor));

Hope it helps.

Upvotes: 4

Related Questions