弹性搜索在单个查询中查找两个字段的总和

时间:2014-06-27 06:04:26

标签: elasticsearch

我需要在单个查询中查找两个字段的总和。我已设法找到一个字段的总和,但在单个查询中添加两个攻击面临困难。

我的json看起来像以下方式

{
    "_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"
    }
 } 

我的搜索查询

{
   "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"
         }
      }
   }
}

如何在一个查询中加入两个攻击?请帮我解决这个问题。谢谢

2 个答案:

答案 0 :(得分:1)

可以有多个子聚合

{
   "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 :(得分:0)

您可以使用脚本

计算总和

示例:

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

您的查询应包含 "脚本" :" doc ['已发送']。值+ doc ['失败']。值"