使用Golang官方Elasticsearch库实现搜索排序报错,求正确写法
解决Go官方Elasticsearch库排序语法报错问题
types.SortCombinations是any类型,不能直接用字面量初始化,你需要使用具体的排序结构体来构建规则,比如字段排序(types.FieldSort)或分数排序(types.ScoreSort)。
正确代码示例
单字段排序(按create_time降序)
get := client.Search().Index(indexName) // 构建字段排序规则 fieldSort := types.FieldSort{ Field: "create_time", Order: types.SortOrderDesc, Missing: "_last", // 可选:指定字段缺失的文档排序位置 UnmappedType: "date", // 可选:处理字段未映射的情况 } // 将具体排序结构体放入SortCombinations切片 sort := []types.SortCombinations{fieldSort} get = get.Request(&search.Request{ Sort: sort, })
多字段排序(先按相关性分数降序,再按create_time降序)
get := client.Search().Index(indexName) scoreSort := types.ScoreSort{ Order: types.SortOrderDesc, } fieldSort := types.FieldSort{ Field: "create_time", Order: types.SortOrderDesc, } sort := []types.SortCombinations{scoreSort, fieldSort} get = get.Request(&search.Request{ Sort: sort, })
关键说明
types.SortCombinations作为any类型,支持ES所有排序类型的结构体,常见的还有:types.GeoDistanceSort:基于地理距离排序types.ScriptSort:基于自定义脚本排序
- 无需直接声明
types.SortCombinations类型变量,把具体排序结构体直接放入切片即可,Go会自动完成类型转换。
内容的提问来源于stack exchange,提问作者khateeb
相关产品推荐
相关产品推荐

