ES统计结果相减的问题

该博客展示了如何在Elasticsearch中通过聚合查询获取特定字段的计数,并进一步计算两个计数之间的差值,例如周一和周二的订单数量差。通过bucket_script聚合函数,可以直接在ES查询中得到结果。
摘要由CSDN通过智能技术生成

使用kibana索引:kibana_sample_data_ecommerce

GET kibana_sample_data_ecommerce/_search
{
  "track_total_hits": true,
  "size": 0,
  "aggs": {
    "terms_day_of_week": {
      "terms": {
        "field": "day_of_week",
        "size": 1000,
        "include": ["Monday","Tuesday"]
      }
    }
  }
}

运行结果

{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4675,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "terms_day_of_week" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "Tuesday",
          "doc_count" : 609
        },
        {
          "key" : "Monday",
          "doc_count" : 579
        }
      ]
    }
  }
}

请问怎么求609和579的差是多少? 可以用es直接计算出来吗

感谢评论区大神的回复:

GET kibana_sample_data_ecommerce/_search
{
  "track_total_hits": true,
  "size": 0,
  "aggs": {
    "top": {
      "terms": {
        "script": "true"
      },
      "aggs": {
        "terms_day_of_week": {
          "filter": {
            "term": {
              "day_of_week": "Monday"
            }
          }
        },
        "terms_day_of_week2": {
          "filter": {
            "term": {
              "day_of_week": "Tuesday"
            }
          }
        },
        "difference": {
          "bucket_script": {
            "buckets_path": {
              "p1": "terms_day_of_week._count",
              "p2": "terms_day_of_week2._count"
            },
            "script": "params.p1 - params.p2"
          }
        }
      }
    }
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值