'Complex aggregation by date and term in elasticsearch

I have an index in elasticsearch with data structure like this:

{"@timestamp":"10:00", "Event": "A"}
{"@timestamp":"10:01", "Event": "B"}
{"@timestamp":"10:02", "Event": "B"}

{"@timestamp":"10:03", "Event": "A"}
{"@timestamp":"10:04", "Event": "B"}

{"@timestamp":"10:05", "Event": "A"}

{"@timestamp":"10:06", "Event": "A"}

I want to count number of A events that have at least one B event before the next A. In the example the answer will be 2:

{"@timestamp":"10:00", "Event": "A"}  # 2 B events
{"@timestamp":"10:01", "Event": "B"}
{"@timestamp":"10:02", "Event": "B"}

{"@timestamp":"10:03", "Event": "A"}  # 1 B event
{"@timestamp":"10:04", "Event": "B"}

{"@timestamp":"10:05", "Event": "A"}  # 0 B event

{"@timestamp":"10:06", "Event": "A"}  # 0 B event

I don't have any idea how to simultaneously aggregate events by their type and timestamp in the way i described.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source