Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

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;"
      }
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

还是我自己来吧.

{
  "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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...