Sort documents and reduce overlapping ranges

Hello,

apologies if the query may be trivial, I am just starting using Elasticsearch. I have an index with usage docs (not nested) with a datetime_start, datetime_end, company_id, user_id, product_id, range_start, range_end and range as an int (how many seconds the product was used for).

What I need to do is to calculate the actual use of the product, so if the same user, for the same product has overlapping ranges as [0, 20] and [15, 30] the actual usage range is 30 seconds and not 35 seconds. I am trying to use painless scripts in line in a GET query, but I keep on getting the error "parser not found" or "Cannot generate an empty script".

GET usage_test/_search
{
  "size": 0,
  "from": 0,
  "stored_fields": [],
  "query": {
    "bool": {
      "must": {
        "match": {
          "company_id": 100
        }
      }
    }
  },
  "aggs": {
    "by_user": {
      "terms": {
        "field": "user_id",
        "size": 100
      },
      "aggs": {
        "by_product": {
          "terms": {
            "field": "product_id",
            "size": 10
          },
          "aggs": {
            "actual_range_sum": {
              "sum": {
                "field": "range",
                "script": {
                  "lang": "painless",
                  "source": "SCRIPT"
                }
              }
            }
          }
        }
      }
    }
  }
}

My main question is: is it possible to achieve something like this either in a query or should I go for creating a scripted field?

Thank you!

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