如何使用Go Olivere/Elastic基于多个字段进行排序 [英] How to sort based on multiple fields with Go olivere/elastic
问题描述
我已经尝试了几天,想知道如何使用Go olivere/弹性
.我正在尝试将其翻译成Go
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" },
],
}
我尝试使用 NewFieldSort()
并在Search Service中提供一些 SortBy()
.它可以与一个 SortBy()
一起正常工作,但不能与两个 SortBy()
一起工作.它返回错误400(错误请求):所有分片均失败[type = search_phase_execution_exception]
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]
这是我的代码
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!
推荐答案
从示例中可以看到,您在示例中使用的 SortBy
函数是可变参数,如下所示: 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)
此请求正文一旦编组为JSON,将如下所示:
Once this request body is marshalled to JSON, it will look like the following:
{
"sort": [
{ "name": { "order": "asc" } },
{ "age": { "order": "desc" } }
]
}
这篇关于如何使用Go Olivere/Elastic基于多个字段进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!