ElasticSearch:使用Java API提供内联脚本

时间:2016-08-11 07:22:10

标签: elasticsearch

我需要使用Java API构建聚合:

GET /sales/t/_search
{
  "aggs": {
    "group_by_month": {
      "terms": {
        "script": "def opDate = new DateTime(doc['date'].date); opDate.getMonthOfYear()",
        "order": {
          "_term": "asc"
        }
      }
    }
  }
}

到目前为止,我已经能够创建terms aggregation,但是,我无法提供脚本:

AggregationBuilders.terms(this.getName()).field(this.getName()).script(??????????)

使用Java API提供内联脚本的方法是什么?

1 个答案:

答案 0 :(得分:2)

就像这样(顺便说一下,不需要field()):

AggregationBuilders.terms(this.getName())
    .script(new Script("def opDate = new DateTime(doc['date'].date); opDate.getMonthOfYear()"))

但请注意,您的脚本可以更简单,如下所示:

doc['date'].date.getMonthOfYear()

原因是doc['date'].date已经是DateTime个实例