简体   繁体   中英

Elasticsearch : How to use multiple filter and calculation in aggregations?

I'm trying to do a function on kibana. I have an index with orders with some fields : datetime1 , datetime2 with format : yyyy-MM-dd HH:mm

First I have to check if datetime1 exist. Secondly I have to check the difference between this 2 datime datetime2 - datetime1 To finish I have to put the result in differents aggs if the difference is:

  • less than 24h
  • between 24 and 48h
  • 48 - 72
  • ....

What I tried :

GET orders/_search
{
  "size": 0,
  "aggs": {
    "test1": {
      "filters": {
        "filters": {
          "exist_datetime1": {
            "exists": {
              "field": "datetime1"
            }
          },
          "24_hours": {
            "script": {
              "script": {
                "source": "doc['datetime2'].value - doc['datetime1'].value < 24",
                "lang": "painless"
              }
            }
          }
        }
      }
    }
  }
}

How can I do multiple filter and do a subtraction between date ? Thank for your help :)

That's a good start, however, I think you need something slightly different. Here is an attempt at providing the ranges your need using the range aggregation powered by your script.

You need to make sure both date fields have values ( query part) and then you can define the buckets you need ( < 24h , 24h - 48h , etc)

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "exists": {
            "field": "datetime1"
          }
        },
        {
          "exists": {
            "field": "datetime2"
          }
        }
      ]
    }
  },
  "aggs": {
    "ranges": {
      "range": {
        "script": {
          "lang": "painless",
          "source": "(doc['datetime2'].value.millis - doc['datetime1'].value.millis) / 3600000"
        },
        "ranges": [
          {
            "to": 24,
            "key": "< 24h"
          },
          {
            "from": 24,
            "to": 48,
            "key": "24h-48h"
          },
          {
            "from": 48,
            "key": "> 48h"
          }
        ]
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM