Elastic search find the sum of two fields in one query

I have a requirement to find the sum of two fields in one query. I managed to find the sum of one field, but with difficulty adding two aggressions to one query.

My json looks like this

{
    "_index": "outboxprov1",
    "_type": "message",
    "_id": "JXpDpNefSkKO-Hij3T9m4w",
    "_score": 1,
    "_source": {
       "team_id": "1fa86701af05a863f59dd0f4b6546b32",
       "created_user": "1a9d05586a8dc3f29b4c8147997391f9",
       "created_ip": "192.168.2.245",
       "folder": 1,
       "post_count": 5,
       "sent": 3,
       "failed": 2,
       "status": 6,
       "message_date": "2014-08-20T14:30Z",
       "created_date": "2014-06-27T04:34:30.885Z"
    }
 } 

My search query

{
   "query": {
      "filtered": {
         "query": {
            "match": {
               "team_id": {
                  "query": "1fa86701af05a863f59dd0f4b6546b32"
               }
            }
         },
         "filter": {
            "and": [
               {
                  "term": {
                     "status": "6"
                  }
               }
            ]
         }
      }
   },
   "aggs": {
      "intraday_return": {
         "sum": {
            "field": "sent"
         }
      }
   },
    "aggs": {
      "intraday_return": {
         "sum": {
            "field": "failed"
         }
      }
   }
}

How to put two aggressions in one request? Please help me solve this problem. Thanks you

+4
source share
2 answers

There may be several sub-aggregates

{
   "query": {
      "filtered": {
         "query": {
            "match": {
               "team_id": {
                  "query": "1fa86701af05a863f59dd0f4b6546b32"
               }
            }
         },
         "filter": {
            "and": [
               {
                  "term": {
                     "status": "6"
                  }
               }
            ]
         }
      }
   },
   "aggs": {
      "intraday_return_sent": {
         "sum": {
            "field": "sent"
         }
      },
      "intraday_return_failed": {
         "sum": {
            "field": "failed"
         }
      }
   }
}
+1
source

You can calculate the amount using a script

Example:

{
   "size": 0,
  "aggregations": {
  "age_ranges": {
     "range": {
        "script": "DateTime.now().year - doc[\"birthdate\"].date.year",
        "ranges": [
           {
              "from": 22,
              "to": 25
           }
        ]
     }
  }
}
}

your request should contain "script": "doc ['sent']. value + doc ['failed']. value"

0
source

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


All Articles