Using Sort API via Elastic.Clients.Elasticsearch 8.1.0 .NET

I have an Elasticsearch cluster, which contains an index called persons. I want to query and sort the documents of the index using the latest Elasticsearch client for .NET (Elastic.Clients.Elasticsearch 8.1.0 .NET). The query I want to execute should like this (note: persons index contains documents with a name field):

GET persons/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "name.keyword": {
        "order": "asc"
      }
    }
  ]
}

Currently I am using this code to execute the above shown query via C#:

var response = await _elasticsearchClient.SearchAsync<Person>(s => s
    .Index("persons")
    .Query(q => q.MatchAll())
    .Sort(so => so
        .Field(f => f.Name.Suffix("keyword"))
        .Score(sc => sc.Order(SortOrder.Asc))));

Unfortunately, this query does not actually sort the documents. Therefore, I want to ask how I could represent the above mentioned query using the 8.1.0 .NET client. The way it used to work in the client with version 7.17 does not work anymore (Sort Usage 7.17).

Hi, @felix-stnr.

Your code is close but is actually setting a score sort. To achieve your goal, you need to provide the FieldSort after providing the field name.

var response = await client.SearchAsync<Person>(s => s
	.Index("persons")
	.Query(q => q.MatchAll())
	.Sort(so => so
		.Field(f => f.Name.Suffix("keyword"), new FieldSort { Order = SortOrder.Asc })));

Thanks, that did the trick for me!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.