【问题标题】:Timestamp regexp in ElasticsearchElasticsearch 中的时间戳正则表达式
【发布时间】:2018-06-20 09:57:40
【问题描述】:

我的目标是在 ElastAlert 中针对这种情况发出警报:午夜到凌晨 2 点之间没有发生任何事件。 (适用于任何日期)。问题是如何对 Elasticsearch 进行查询以匹配除特定时间之外的任何日期,因为您不能在“日期”类型的时间戳上使用正则表达式或通配符。有什么建议吗?

此代码返回“解析失败”:

"range": {
  "timestamp": {
    "gte": "20[0-9]{2}-[0-9]{2}-[0-9]{2}T00:00:00.000Z",
    "lt": "20[0-9]{2}-[0-9]{2}-[0-9]{2}T02:00:00.000Z"
  }
}

【问题讨论】:

  • 你有没有尝试过?请分享以帮助我们更好地帮助您
  • 在正则表达式中,?是一个量词,不允许对一个量词进行量化。因此,要匹配任何数字,您可以使用[0-9]。这有帮助吗? gte": "20[0-9]{2}-[0-9]{2}-[0-9]{2}T00:00:00[.]000Z",?
  • 好吧,你是对的:'?'应该 '。'截至link。更正它。
  • 并且. 应该被转义或在[] ([.]) 中使用,否则它将匹配除换行符以外的任何符号。
  • 我仍然认为问题在于无法结合正则表达式和时间戳。我怀疑时间戳实际上是一个纪元时间,因此在日期中间进行正则表达式在纪元时间中表达得太复杂了。

标签: regex elasticsearch elasticsearch-dsl elastalert


【解决方案1】:

在自定义规则中处理它是理想的。

我编写了以下代码来执行相同类型的过滤: 请注意,使用的依赖项(dateutil、elastalert.utils)已经与 elastalert 框架捆绑在一起。

import dateutil.parser

from ruletypes import RuleType

# elastalert.util includes useful utility functions
# such as converting from timestamp to datetime obj
from util import ts_to_dt

# Modified version of http://elastalert.readthedocs.io/en/latest/recipes/adding_rules.html#tutorial
# to catch events happening outside a certain time range
class OutOfTimeRangeRule(RuleType):
    """ Match if input time is outside the given range """

    # Time range specified by including the following properties in the rule:
    required_options = set(['time_start', 'time_end'])

    # add_data will be called each time Elasticsearch is queried.
    # data is a list of documents from Elasticsearch, sorted by timestamp,
    # including all the fields that the config specifies with "include"
    def add_data(self, data):
        for document in data:
            # Convert the timestamp to a time object
            login_time = document['@timestamp'].time()

            # Convert time_start and time_end to time objects
            time_start = dateutil.parser.parse(self.rules['time_start']).time()
            time_end = dateutil.parser.parse(self.rules['time_end']).time()

            # If time is outside office hours
            if login_time < time_start or login_time > time_end:

                # To add a match, use self.add_match
                self.add_match(document)

    # The results of get_match_str will appear in the alert text
    def get_match_str(self, match):
        return "logged in outside %s and %s" % (self.rules['time_start'], self.rules['time_end'])

    def garbage_collect(self, timestamp):
        pass

【讨论】:

    【解决方案2】:

    我无权编写自定义规则,所以我的解决方案是在 logstash 中进行更改。添加了字段 hour_of_day,其中的值来自时间戳。因此,我们可以使用这样的过滤器创建一个扁平化规则:

    filter:
     - query:
          query_string:
            query: "hour_of_day: 0 OR hour_of_day: 1"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      相关资源
      最近更新 更多