【问题标题】:Scripted Aggregation Calculation with unexpected results具有意外结果的脚本聚合计算
【发布时间】:2020-03-14 22:07:04
【问题描述】:

首先,我对 ES / SK 有点陌生,对聚合更是如此。

这是我的 aggs 结构:

  aggs: {
    all_budgets: {
      sum: {
        field: :amount
      }
    },
    all_forecasts: {
      sum: {
        field: :forecast_total
      }
    },
    all_variance: {
      sum: {
        script: "doc['forecast_total'].value - doc['amount'].value"
      }
    },
    all_variance_p: {
      sum: {
        script: "(doc['forecast_total'].value - doc['amount'].value) / doc['amount'].value"
      }
    }

  }

我基本上是想得到我所有预算的总和,总支出,然后是超出/低于预算和相应的百分比。这是我的输出:

{
  "all_forecasts": {
    "doc_count": 2,
    "value": 173604.0
  },
  "all_budgets": {
    "doc_count": 2,
    "value": 185437.0
  },
  "all_variance_p": {
    "doc_count": 2,
    "value": "0.33694326595832774"
  },
  "all_variance": {
    "doc_count": 2,
    "value": -11833.0
  }
}

“0.33694326595832774”值错误 - 应为“-0.06408106257”(即 -11833.0 / 185437.0)。前两个脚本有效,我怀疑我只是不明白这些脚本是如何工作的。

【问题讨论】:

  • 请添加映射和数据

标签: elasticsearch searchkick


【解决方案1】:

在除法之前尝试将您的号码转换为相同的datatype。例如((float)(doc['forecast_total'].value) - (float)(doc['amount'].value)) / (float)(doc['amount'].value))

【讨论】:

  • 我知道问题出在哪里 - ES 正在计算每个文档的 all_variance_p,然后将它们全部相加。这就是all_variance 工作正常的原因。我需要访问all_budgetsall_forecasts 的最终值进行计算。
  • 哦!然后看看管道聚合。这些使您能够处理其他聚合的结果。
【解决方案2】:

响应您的 cmets 访问 all_budgets 和 all_forecasts 的最终值以进行进一步计算,您可以使用bucket script aggregation,它可以使用桶路径访问父聚合。由于它需要处理桶,因此您需要添加一个父聚合 ex date_histogram,它在给定的时间间隔(年或月或日期等)中拆分文档

{
  "size": 0,
  "aggs": {
    "year_interval": {
      "date_histogram": {
        "field": "timestamp",
        "interval": "year"
      },
      "aggs": {
        "all_budgets": {
          "sum": {
            "field": "amount"
          }
        },
        "all_forecasts": {
          "sum": {
            "field": "forecast"
          }
        },
        "all_variance": {
          "bucket_script": {
            "buckets_path": {
              "total_forecast":"all_forecasts",
              "total_budget":"all_budgets"
            },
            "script": "params.total_forecast-params.total_budget"
          }
        },
        "all_variance_p": {
          "bucket_script": {
            "buckets_path": {
              "variance":"all_variance",
              "budget":"all_budgets"
            },
            "script": "params.variance/params.budget"
          }
        }
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 2018-04-25
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多