How to subtract aggregated minimum from aggreagate max (difference) in ES?

How to write an ES query to find the difference between the maximum and minimum field value?

I am new to elasticity search. In my case I spend a lot of events along with session_id and time searching for elasticity. My event structure

Event_name string    `json:"Event_name"`
Client_id  string    `json:"Client_id"`
App_id     string    `json:"App_id"`
Session_id string    `json:"Session_id"`
User_id    string    `json:"User_id"`
Ip_address string    `json:"Ip_address"`
Latitude   int64     `json:"Latitude"`
Longitude  int64     `json:"Longitude"`
Event_time time.Time `json:"Time"`

I want to find the session_id lifetime based on the events that were sent. To do this, I can get the maximum Event_time event and the minimum Event_time event for a specific session_id at the following ES request.

{  
  "size": 0,
  "query": {
     "match": {
        "Session_id": "dummySessionId"
     }
  },
   "aggs": {
      "max_time": {
         "max": {
           "field": "Time"
          }
       },
       "min_time":{
          "min": {
            "field": "Time"
          }
       }
    }
  }

But I want it for sure (max_time - min_time) How to write an ES request for the same ????

+4
source share
3 answers

elasticsearch 1.1.1, , , elasticsearch. , .

, @eliasah.

.

+2

1.5.1, Scripted Metric Aggregation, . , . .

POST test_time

POST test_time/data/1
{"Session_id":1234,"Event_time":"2014-01-01T12:00:00"}

POST test_time/data/3
{"Session_id":1234,"Event_time":"2014-01-01T14:00:00"}

GET /test_time/_search
{
  "size": 0,
  "aggs": {
    "by_user": {
      "terms": {
        "field": "Session_id"
      },
      "aggs": {
        "session_lenght_sec": {
          "scripted_metric": {
            "map_script": "_agg['v'] = doc['Event_time'].value",
            "reduce_script": "min = null; max = null; for (a in _aggs) {if (min == null || a.v < min) { min = a.v}; if (max == null || a.v > max) { max = a.v }}; return (max-min)/1000"
          }
        }
      }
    }
  }
}

###### RESPONSE #######
{
   ...,
   "aggregations": {
      "by_user": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": 1234,
               "doc_count": 2,
               "session_lenght_sec": {
                  "value": "7200"
               }
            }
         ]
      }
   }
}
+1

Source: https://habr.com/ru/post/1539539/


All Articles