Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort based on multiple fields with Go olivere/elastic

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!

like image 605
jonathanjordy Avatar asked Dec 19 '25 04:12

jonathanjordy


1 Answers

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" } }
    ]
}
like image 152
blackgreen Avatar answered Dec 21 '25 21:12

blackgreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!