title: Defining a time range for aggregation in elasticsearch
body: <p>I've got an index in ElasticSearch with documents having info about user connections to my platform. I want to build a query with day aggregation where I can count all users connected every day between two given dates. </p>
  
  <p>I have 3 relevant fields to do so: <code>user_id</code>, <code>connection_time_start</code>, <code>connection_time_end</code>. I was doing the query this way:</p>
  
  <pre><code>{
    "size": 0,
    "query": {
      "bool": {
        "must": [
          {
            "range": {
              "connection_time_start": {
                "lte": "2017-08-04T23:59:59"
              }
            }
          },
          {
            "range": {
              "connection_time_end": {
                "gte": "2017-08-02T00:00:00"
              }
            }
          }
        ]
      }
    },
    "aggs": {
      "franja_horaria": {
        "date_histogram": {
          "field": "connection_time_start",
          "interval": "day",
          "format": "yyyy-MM-dd"
        },
        "aggs": {
          "ids": {
            "cardinality": {
              "field": "user_id"
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>This query has given as a result buckets containing the number of users that had the starting connection at day 2, 3 &amp; 4 of August. The problem is that there are users with connections starting on day 2 and ending on day 3 and even on day 4.</p>
  
  <p>These users should compute for the connected user count for each day but as I'm doing the aggregation with the connection_time_start only counts for that day.</p>
  
  <p>I've tried to add a range in the aggregation some thing like this(<a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-aggregations-bucket-daterange-aggregation.html" rel="nofollow noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-aggregations-bucket-daterange-aggregation.html</a>) but haven't got a good result.</p>
  
  <p>Can anybody help me with this? Thanks in advance!</p>