elasticsearch 通过painless脚本排序 java客户端

通过脚本排序

数据内容:

    "_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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值