elasticsearch中使用scripted_metric进行排序

一个用户拥有id,mobile,nickname以及一个huanbi数组。现在已经可以通过scripted_metric将符合条件的huanbi数据汇总到一起,但是在最终reduce阶段的时候尝试进行排序未得到想要的结果,虽然使用java脚本指定要求排序,但是最终出来的结果依旧是乱序,望大神指点迷津。(mapping及代码在下面)

mapping:

{
  "dgcrm-allinone" : {
    "mappings" : {
      "properties" : {
        "huanbi" : {
          "type" : "nested",
          "properties" : {
            "evaluation" : {
              "type" : "keyword"
            },
            "finalizationScore" : {
              "type" : "integer"
            },
            "id" : {
              "type" : "integer"
            },
            "sumScore" : {
              "type" : "integer"
            }
          }
        },
        "id" : {
          "type" : "long"
        },
        "mobile" : {
          "type" : "keyword"
        },
        "nickname" : {
          "type" : "keyword"
        }
      }
    }
  }
}

脚本如下:
POST /dgcrm-allinone/_search?filter_path=aggregations

{
  "aggs":{
    "allHuanbi":{
      "scripted_metric": {
        "init_script": "state.huanbi=new ArrayList();",
        "map_script": "for(item in params._source.huanbi){state.huanbi.add(item);}",
        "combine_script": "return state;", 
        "reduce_script": "ArrayList finalResult = new ArrayList();for(s in states){finalResult.add(s)}Collections.sort(finalResult, Collections.reverseOrder());return finalResult;"
      }
    }
  }
}
阅读 3.6k
1 个回答

还是我自己来吧.

{
  "aggs":{
    "allHuanbi":{
      "scripted_metric": {
        "init_script": "state.huanbi=[]",
        "map_script": "for(item in params._source.huanbi){state.huanbi.add(item);}",
        "combine_script": "return state.huanbi", 
        "reduce_script": "ArrayList huanbis=new ArrayList();for(stateI in states){for(s in stateI){huanbis.add(s)}}huanbis.sort(Comparator.comparing(h->h.get('id'), Comparator.nullsLast(Comparator.naturalOrder())));return huanbis;"
      }
    }
  }
}

如果想逆序排列的话要么把naturalOrder改成reverseOrder,还有一种就是把naturalOrder()变成naturalOrder().reversed()

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进