2016-11-07 246 views
1

通过下面的汇总和使用ES5,我想根据给定的时区(作为来自TZ数据库的标识符提供)来获取dayOfWeek & hourOfDay。在Elasticsearch中,如何将时区应用于脚本日期操作?

如何编辑"doc['created'].date.dayOfWeek'来调整偏移量?

aggs: { 
     dayOfWeek: { 
     terms: { 
      script: { 
      inline: "doc['created'].date.dayOfWeek", 
      lang: 'painless', 
      }, 
     }, 
     aggs: { 
      hourOfDay: { 
      terms: { 
       script: { 
       inline: "doc['created'].date.hourOfDay", 
       lang: 'painless', 
       }, 
      }, 
      }, 
     }, 
     }, 
    }, 

回答

2

像这样的东西应该工作:

{ 
    "size": 0, 
    "aggregations": { 
    "dayOfWeek": { 
     "terms": { 
     "script": { 
      "inline": "doc['created'].date.setZone(org.joda.time.DateTimeZone.forID(tz)); doc['created'].date.dayOfWeek", 
      "lang": "groovy", 
      "params": { 
      "tz": "Europe/London" 
      } 
     } 
     }, 
     "aggs": { 
     "hourOfDay": { 
      "terms": { 
      "script": { 
       "inline": "doc['created'].date.setZone(org.joda.time.DateTimeZone.forID(tz)); doc['created'].date.hourOfDay", 
       "lang": "groovy", 
       "params": { 
       "tz": "Europe/London" 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
} 

你可能会需要通过添加script.engine.groovy.inline.aggs: on到elasticsearch.yml文件启用常规内嵌脚本。参见:This discussion

注意。以上不会无痛苦工作,因为它被锁定,并且does not allow you to edit the whitelist.

+0

这给了我错误:'Variable [DateTimeZone]没有被定义.'甚至在'java.policy'文件中有'org.joda。*'。我不是java开发者,但默认情况下已经包含了'java.time.zone'? (基于:https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-painless.html#painless-api) –

+0

我已修改为包含完全限定的类名称。日期字段是Joda'DateTime'实例,因此为什么我不使用普通Java'TimeZone'类 – Val

+0

这给了我'变量[org]没有定义'。我修改了白名单,方法是创建'/ usr/local/etc/elasticsearch/.java.policy'并放置'grant {permission org.elasticsearch.script.ClassPermission“org.joda。*”; };'在里面,但也许ES不会选择这个?它通过Homebrew安装。 –

1

找到解决方案使用无痛。因为他们正在从Joda将elasticsearch迁移到native java.time,所以对Joda的支持并不好。

{ 
    "size": 0, 
    "aggregations": { 
    "dayOfWeek": { 
     "terms": { 
     "script": { 
      "inline": "Instant.ofEpochMilli(doc.created.date.millis).atZone(ZoneId.of(params.tz)).dayOfWeek", 
      "params": { 
      "tz": "Europe/London" 
      } 
     } 
     }, 
     "aggs": { 
     "hourOfDay": { 
      "terms": { 
      "script": { 
       "inline": "Instant.ofEpochMilli(doc.created.date.millis).atZone(ZoneId.of(params.tz)).hour", 
       "params": { 
        "tz": "Europe/London" 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
}