I've been trying for days to know how to sort based on multiple fields with Go olivere/elastic. I'm trying to translate this into Go
{
"sort" : [
"name",
{ "age" : "desc" },
],
}
I've tried to use the NewFieldSort() and give some SortBy() in the Search Service. It works fine with one SortBy() but won't work with two SortBy(). It returns Error 400 (Bad Request): all shards failed [type=search_phase_execution_exception]
Here's my code
sortQuery1 := elastic.NewFieldSort("name")
sortQuery2 := elastic.NewFieldSort("age").Desc()
searchService := esclient.Search().
Index("students").
SortBy(sortQuery1).
SortBy(sortQuery2)
searchResult, err := searchService.Do(ctx)
Do you guys have any suggestions on what to try? Thanks in advance!
The SortBy function you're using in your example is variadic, as you can see from the signature: SortBy(sorter ...Sorter) *SearchService.
So you only need to call it once with both your filter conditions:
sortQuery1 := elastic.NewFieldSort("name")
sortQuery2 := elastic.NewFieldSort("age").Desc()
searchService := client.Search().
Index("students").
SortBy(sortQuery1, sortQuery2)
Once this request body is marshalled to JSON, it will look like the following:
{
"sort": [
{ "name": { "order": "asc" } },
{ "age": { "order": "desc" } }
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With