通过脚本排序
数据内容:
"_source": {
"userid": 123,
"city": [
102
],
"expection2": [
2496
],
"sex": 1,
"age": 31,
"cate_score": [
"580:0.9",
"581:0.5",
"593:0.2",
"706:0.1",
"606:0.65"
],
"lmodtime": 1459347878,
}
}
根据业务方传入的类型数据去cate_score字段里面去找,如果找到对应的类型那么根据返回的类型数据进行排序。比如传入580那么所有的数据按照cate_score中580的数据分值数据去排序
String scriptCode="脚本内容";
System.out.println(scriptCode);
Map<String, Object> params = new HashMap<>();
params.put("cate", 606);
Script script = new Script(ScriptType.INLINE,"painless",scriptCode,params);
SortBuilder sortBuilder = SortBuilders.scriptSort(script, ScriptSortBuilder.ScriptSortType.NUMBER);
sortBuilder.order(SortOrder.DESC);
SearchSourceBuilder sb = new SearchSourceBuilder();
sb.sort(sortBuilder);
System.out.println(sb.toString());
SearchResponse search = client.search(new SearchRequest(new String[] { "supin_index_test" }, sb));
SearchHit[] hits = search.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsMap());
}
painless脚本:
int size = doc['cate_score.keyword'].length;
double score = -0.1;
int targetCate = params.cate;
for (int i = 0; i < size; i++) {
def path = doc['cate_score.keyword'][i];
int flag = path.lastIndexOf(':');
double get_score = Double.parseDouble(path.substring(flag + 1));
int get_cate = Integer.parseInt(path.substring(0, flag));
if (get_cate == targetCate) {
score = get_score;
break;
}
}
return score