Elastic aggregation for timeline of a searched field based on timestamp

We are using elastic version: 6.8

I need help with a sample query that can solve below use case.

Sample data:

We have books index, that can travel in which zone a book was and when.

{'zone': 'z1', book: 'book1', timestamp: '01/01/2020'}
{'zone': 'z1', book: 'book1', timestamp: '03/01/2020'}
{'zone': 'z2', book: 'book1', timestamp: '04/01/2020'}
{'zone': 'z2', book: 'book1', timestamp: '05/01/2020'}
{'zone': 'z2', book: 'book1', timestamp: '10/01/2020'}
{'zone': 'z2', book: 'book1', timestamp: '12/01/2020'}
{'zone': 'z1', book: 'book1', timestamp: '15/01/2020'}
{'zone': 'z1', book: 'book1', timestamp: '16/01/2020'}
{'zone': 'z1', book: 'book1', timestamp: '20/01/2020'}

I want a query that can return the book's complete journey accross zones, while a book does back and forth in zones.

Expected Output if we query for book1:

[ 
    {
        zone: 'z1'
        start: '01/01/2020'
        end: '04/01/2020'
    },
    {
        zone: 'z2'
        start: '05/03/2020'
        end: '12/01/2020'
    },
    {
        zone: 'z1'
        start: '15/03/2020'
        end: '20/01/2020'
    }
]

This is what I came up with so far.

GET /book/_search
{
  "query": {
      "bool": {
          "must": [
              {
                  "match": {
                      "book": "book1"
                  }
              }
          ]
      }
  },
  "size": 0,
  "aggs": {
        "zoneList": {
          "terms": {
            "field": "zone",
            "size": 1000
        },
        "aggs": {
          "first_seen": {
           "top_hits": {
              "size": 1,
              "sort": [
                 {
                    "timestamp": {
                       "order": "asc"
                    }
                 }
              ],
              "_source": {
                  "includes": ["timestamp"]
                }
              }
          },
          "last_seen": {
             "top_hits": {
                "size": 1,
                "sort": [
                   {
                      "timestamp": {
                         "order": "desc"
                      }
                   }
                ],
                "_source": {
                  "includes": ["timestamp"]
                }
             }
          }  
        }
      }
  }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.