需求背景:
從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}}}
}