# Sort documents and reduce overlapping ranges

**URL:** <https://discuss.elastic.co/t/sort-documents-and-reduce-overlapping-ranges/260526>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [January 8, 2021, 9:50am UTC](https://discuss.elastic.co/t/sort-documents-and-reduce-overlapping-ranges/260526 "2021-01-08T09:50:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lucre](https://avatars.discourse-cdn.com/v4/letter/l/b9e5f3/32.png) [@lucre](https://discuss.elastic.co/u/lucre)\
**Post date:** [January 8, 2021, 9:50am UTC](https://discuss.elastic.co/t/sort-documents-and-reduce-overlapping-ranges/260526/1 "2021-01-08T09:50:42Z")

</div>

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".

```auto
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!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [February 5, 2021, 9:50am UTC](https://discuss.elastic.co/t/sort-documents-and-reduce-overlapping-ranges/260526/2 "2021-02-05T09:50:45Z")

</div>

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