elasticsearch 如何计算ELK上多重聚集结果之间差异?

mm9b1k5b  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(1)|浏览(168)

我有一个文档的索引:

id:1
type: Deposit
value:12
timestamp:2022.10.09T00.00.00

#### 

id:2 
type: withdraw
value:15
timestamp:2022.10.9T00.00.00

#### 

id:3
type: Deposit
value:17
timestamp:2022.10.09T11.00.00
....

因此,我运行多个聚合,例如:

"aggs": {
    "s1": {
      "terms": {
        "field": "type",
        "size": 10
      },
      "aggs": {
        "SUM": {
          "sum": {
            "field": "value"
          }
        }
      }
    }

我的结果是:
“bucket”:[ {“key”:“存款”,“单据计数”:9、“SO”:{“值”:78983 } },{“钥匙”:“撤销”,“单据_计数”:9、“SO”:{“值”:小行星777445
但是我想计算“存款值-提款值”。这是什么查询???

n8ghc7c1

n8ghc7c11#

您可以使用bucket_script聚总来执行此作业。bucket命令档聚总如下所示。

"diff": {
          "bucket_script": {
            "buckets_path": {
              "my_var1": "s1['field_value']>s2",
              "my_var2": "s1['field_value']>s2"
            },
            "script": "params.my_var1 - params.my_var2"
          }
        }

我在下面分享细节和解决方案。

POST test_stackoverflow_question/_bulk
{"index":{}}
{"id":"1", "type": "Deposit", "value":12, "timestamp":"2022.10.09T00.00.00"}
{"index":{}}
{"id":"2", "type": "withdraw", "value":15, "timestamp":"2022.10.9T00.00.00"}
{"index":{}}
{"id":"3", "type": "Deposit", "value":17, "timestamp":"2022.10.09T11.00.00"}

如果术语指的是多部分聚合(如agg),则同级管道ag可以选择从多存储桶中选择特定键。例如,bucket_script可以选择(通过包键)两个自定义存储桶来执行计算:

GET test_stackoverflow_question/_search
{
  "size": 0,
  "aggs": {
    "calculate_diff": {
      "filters": {
        "filters": {
          "all": {
            "match_all": {}
          }
        }
      },
      "aggs": {
        "s1": {
          "terms": {
            "field": "type.keyword",
            "size": 10
          },
          "aggs": {
            "s2": {
              "sum": {
                "field": "value"
              }
            }
          }
        },
        "diff": {
          "bucket_script": {
            "buckets_path": {
              "my_var1": "s1['Deposit']>s2",
              "my_var2": "s1['withdraw']>s2"
            },
            "script": "params.my_var1 - params.my_var2"
          }
        }
      }
    }
  }
}

参考编号:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.htmlhttps://www.elastic.co/guide/en/elasticsearch/reference/7.17/search-aggregations-pipeline.html

相关问题