elasticsearch - 聚合值的总和

elasticsearch - sum of aggregated values

假设我有以下数据

{
    "quantity" : 1,
    "amount" : 10,
    "discount" : 1
}

{
    "quantity" : 4,
    "amount" : 12,
    "discount" : 2
}

我可以使用以下查询获得这些的汇总结果,

{
   ...
   "aggs" : {
     "sumOfQuantity" : {
        "sum" : {
           "field" : "quantity"
        }
     },
     "SumOfAmount" : {
        "sum" : {
           "field" : "amount"
        }
     },
     "SumOfDiscount" : {
        "sum" : {
           "field" : "discount"
        }
     }
   }
}

使用上面的查询,我可以获得必填字段的总和。现在我还想减去聚合的 SumOfAmount 和 SumOfDiscount (SumOfAmount - SumOfDiscount)。我怎样才能实现它?

提前致谢!!

您可以使用run time mapping

查询

{
  "size": 0,
  "runtime_mappings": {
    "net_amount": {
      "type": "double",
      "script": {
        "source": "emit(doc['amount'].value - doc['discount'].value)"
      }
    }
  },
  "aggs": {
    "sumOfQuantity": {
      "sum": {
        "field": "quantity"
      }
    },
    "SumOfAmount": {
      "sum": {
        "field": "amount"
      }
    },
    "SumOfDiscount": {
      "sum": {
        "field": "discount"
      }
    },
    "NetAmmount":{
      "sum": {
        "field": "net_amount"
      }
    }
  }
}

结果

 "aggregations" : {
    "sumOfQuantity" : {
      "value" : 5.0
    },
    "NetAmmount" : {
      "value" : 19.0
    },
    "SumOfAmount" : {
      "value" : 22.0
    },
    "SumOfDiscount" : {
      "value" : 3.0
    }
  }