每天在 Elasticsearch 中搜索事件的第一次发生

Searching Elasticsearch for first occurance of an event each day

我们使用 Logstash 接收日志,传递给 Elasticsearch,并使用 Kibana 浏览。很常见的设置。

每个条目中的一个字段是@timestamp,示例内容为03/18/2015 18:02:52。我应该使用什么过滤器来仅显示每天的第一个条目?

我不相信您可以使用过滤器来做到这一点 - 一天中的第一个不是 属性 您可以通过查看单个文档来确定的。但是,您应该能够通过聚合来做到这一点:首先使用 date_histogram with interval day, to group the events by day. Then use the top_hits 聚合进行聚合,每天提取一个结果(需要 elasticsearch 1.3 或更高版本)。您的查询应如下所示

{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "by-day": {
      "date_histogram": {
        "field": "timestamp",
        "interval": "day"
      },
      "aggs": {
        "top_for_day": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "timestamp": {
                  "order": "asc"
                }
              }
            ]
          }
        }
      }
    }
  }
}

应该会产生如下结果(为简洁起见略微删减)

{
  "aggregations": {
    "by-day": {
      "buckets": [
        {
          "key_as_string": "2015-02-01T00:00:00.000Z",
          "key": 1422748800000,
          "doc_count": 7635,
          "top_for_day": {
            "hits": {
              "total": 7635,
              "max_score": null,
              "hits": [
                {
                  "_index": "events-2015-02",
                  "_type": "event",
                  "_id": "c64f85ac-a870-441f-bedb-e24db47fd02a",
                  "_score": null,
                  "_source": {
                    "eventTime": "2015-02-01T00:00:26Z"
                  },
                  "sort": [
                    1422748826000
                  ]
                }
              ]
            }
          }
        },
        {
          "key_as_string": "2015-02-02T00:00:00.000Z",
          "key": 1422835200000,
          "doc_count": 8182,
          "top_for_day": {
            "hits": {
              "total": 8182,
              "max_score": null,
              "hits": [
                {
                  "_index": "events-2015-02",
                  "_type": "event",
                  "_id": "c544278d-9f51-41a8-827b-9c70c0a057ca",
                  "_score": null,
                  "_source": {
                    "timestamp": "2015-02-02T00:00:19Z"
                  },
                  "sort": [
                    1422835219000
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  }
}