es实现order by field

mysql的order by field语法,支持对某个字段自定义排序规则。
比如查询人员信息时,先按性别排序,先男后女,再按id降序排序。

select * from user_info order by field(gender, 'Male', 'Female'), id desc; 


es如果要实现同样的效果,java代码如下

// 定义一个Map, key为gender字段值,value为分数
Map sortMap = new HashMap<>(2);
int sort = 1;
sortMap.put("Male", sort++);
sortMap.put("Female", sort++);

// 编写painless脚本
String scriptText ="params.sortMap[doc['gender'].value]";
Map params = new HashMap<>(1);
params.put("sortMap", sortMap);
Script script = new Script(ScriptType.INLINE, "painless", scriptText,params);
ScriptSortBuilder genderSortBuilder = SortBuilders.scriptSort(script,ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC);

// 构造查询器
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 先按性别排
searchSourceBuilder.sort(genderSortBuilder);
// 再按id降序排
searchSourceBuilder.sort("_id", SortOrder.DESC);

最终DSL如下

{
    "from":0,
    "size":10,
    "query":{
        "match_all": {}
    },
    "sort":[
        {
            "_script":{
                "script":{
                    "source":"params.sortMap[doc['gender'].value]",
                    "lang":"painless",
                    "params":{
                        "sortMap":{
                            "Male":1,
                            "Female":2
                        }
                    }
                },
                "type":"number",
                "order":"asc"
            }
        },
        {
            "_id":{
                "order":"desc"
            }
        }
    ]
}



备注
ES SDK版本: 6.8.0.8

你可能感兴趣的:(es实现order by field)