elasticsearch _script 脚本排序

时间:2021-09-27 02:32:11
具体脚本语法请自行搜索“Groovy”语法。
{
"from" : 0,
"size" : 5,
"query" : {
"bool" : {
"filter" : {
"terms" : {
"id" : [ "33009", "30025", "20281", "16221", "103859", "102738" ]
}
}
}
},
"sort" : [ {
"_script" : {
"script" : {
"inline" : "def boolean bo1 = false;def boolean bo2 = false;def zhenghoumc = doc['binganList.zhenghoumc.raw'];def yongyao=doc['binganList.zhenciList.zhongyaozlList.zhongyaozcList.danweiymc.raw'];for(i in 0..<yongyao.size()){if(yongyao[i]!=''){bo1=true;break}};for(i in 0..<zhenghoumc.size()){if(zhenghoumc[i]!=''){bo2=true;break}};bo2==false&&bo1==false?0:(bo2==false&&bo1==true?1:(bo1==true&&bo2==true?10:9))"
},
"type" : "number",
"order" : "desc"
}
} ]
}
boolQuery.filter(QueryBuilders.termsQuery("id", list));
SearchRequestBuilder builder = this.client.prepareSearch("cmhealth1");
builder.setTypes("docase");
builder.setQuery(boolQuery);
// SortBuilder aa = SortBuilders.fieldSort("yongyao").;
// Script aa = new ScriptSortBuilder("''==doc['source'].value?0:1","number").order(SortOrder.ASC); Script script=new Script("def boolean bo1 = false;def boolean bo2 = false;"
+ "def zhenghoumc = doc['binganList.zhenghoumc.raw'];"
+ "def yongyao=doc['binganList.zhenciList.zhongyaozlList.zhongyaozcList.danweiymc.raw'];"
+ "for(i in 0..<yongyao.size()){if(yongyao[i]!=''){bo1=true;break}};"
+ "for(i in 0..<zhenghoumc.size()){if(zhenghoumc[i]!=''){bo2=true;break}};"
+ "bo2==false&&bo1==false?0:(bo2==false&&bo1==true?1:(bo1==true&&bo2==true?10:9))");
ScriptSortBuilder scriptSortBuilder = SortBuilders.scriptSort(script, "number").order(SortOrder.DESC);
// builder.addSort("binganList.zhenghoumc", SortOrder.DESC);
builder.addSort(scriptSortBuilder);
builder.setFrom(pageNum);
builder.setSize(pageSize);
SearchResponse response = builder.get();