需求背景:
从es查询数据出来的时候,要求type为CATALOG的数据排在最前面,也就是目录类型的要放在最前面,而且要求按照层级排序,从L1到L5顺序排序
直接上解法:
{
//查询条件
"query": {
"bool": {
//必须满足
"must": [
{
"term": {
"status": "PUBLISHED"
}
},
{
"bool": {
//多条件满足一个即可
"should": {
"terms": {
"subAssetsType": [
"CATALOG",
"TABLE",
"VIEW",
"DATA_OBJECT",
"REPORT",
"FILE"
]
}
}
}
}
]
}
},
//返回的条数
"size":200,
//排序条件
"sort": [
{
"_script": {
"type": "number",
"script": {
"lang": "painless",
//这里主要就是把目标的分数set为大值,这里不支持split方法和charAt方法也不支持,可以用contains和indexOf方法
"source": "int catalogPriority = doc['subAssetsType'].value == 'CATALOG' ? 1 : 0; int slashCount = 0; if (catalogPriority == 1 && doc.containsKey('catalogPath')) { String catalogPathValue = doc['catalogPath'].value; if (catalogPathValue != null && !catalogPathValue.isEmpty()) { for (int i = 0; i < catalogPathValue.length(); i++) {if (catalogPathValue.substring(i, i + 1).contains('/')) {slashCount++;}} } } return catalogPriority * 1000 - slashCount;"
},
//在这里进行倒叙,这样目标数据就排到前面了
"order": "desc"
}
},{
"_score":"DESC"
}
],
//聚合条件
"aggs": {
"subs": {
"terms": {
//聚合的字段,类似group by subAssetsType
"field": "subAssetsType",
"order": { // 排序方式
"_count": "asc" // 按照计数降序排列
},
"size": 100
}
}
}
}