'Reverse nested aggregation in date histogram ElasticSearch

I have some problems combining data from different levels in the date histogram. Elastic documentation gives an example that helps to deal with the case when the date in histogram is retrieved from the current level of nesting and aggregation uses the level upper, so reverse_nested helps. But what to do if the situation is mirrored? Like the aggregation uses the current level of nesting and date lives on the uppers level?

Let's say I have the next data structure:

  {
    "_source": {
      "order_uuid": "...",
      "created_at": "...",
      "status": "...",
      "subtotal": 100,
      "items": [
        {
          "item_id": 1,
          "price": 1000,
          "units": 1,
        }
      ],
    }
  }

And I want to have date histogram with created_at field for each item. So I want to have smth like this:

{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "items": {
      "nested": {
        "path": "items"
      },
      "aggs": {
        "data": {
          "terms": {
            "field": "items.item_id"
          },
          "aggs": {
            "reversed": {
              "aggs": {
                "sales_per_day": {
                  "date_histogram": {
                    "reverse_nested": {},
                    "field": "created_at", #<- not nested
                    "calendar_interval": "day",
                    "format": "yyyy-MM-dd",
                  },
                  "aggs": {
                    "units_sum": {
                      "sum": {"field": "items.units"} #<- nested
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

This example doesn't work obviously because you can't use reverse_nested inside date_histogram (at least I don't know how) but it gives the impression of what I what it to be.

Does anyone have ideas on how to deal with it without reorganizing the mapping? Ideas are appreciated.



Sources

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

Source: Stack Overflow

Solution Source