【问题标题】:ElasticSearch aggregation - buckets/scripted_metricElasticSearch 聚合 - buckets/scripted_metric
【发布时间】:2022-01-15 01:24:21
【问题描述】:

我尝试为索引中的每个文档计算速率函数 rate(val,ts)= v2-v1/t2-t1

我的映射格式为:{ "name":keyword","value":"double","timestamp":"integer"}。

例如,如果我的索引中有 2 个文档:

doc1:{"name":name1,"value":5,"timestamp":2 } doc2: {name":name1,"value":10,"timestamp":3 },

我需要得到 result(ts=3) = (10-5)/(3-2)

在 elasticsearch 中有没有办法做到这一点?

我尝试以这种形式编写自己的指标脚本:

GET test1/_search
{
"size":15,
"aggs":{
  "sum_the_hard_way": {
    "scripted_metric": {
      "init_script": {
        "source": "state.values = []; state.timestamps = [];"
      },
      "map_script": {
        "source": "state.values.add(doc['value'].value);state.timestamps.add(doc['timestamp'].value);"
      },
      "combine_script": {
        "source": "def rates = []; for ( int i = 0; i <= state.values.size()-1 ; i++ ) { rate[i+1] = (state.value[i+1]- state.value[i])/(state.timestamp[i+1]- state.timestamp[i]);} return values"
      },
      "reduce_script": {
        "source": "def vals = []; for (a in states) { vals.add(a) } return vals"
      }
    }
  }
}
}

但它不起作用,我得到了

“原因”:“index_out_of_bounds_exception:索引 0 超出范围 长度

提前谢谢你!

【问题讨论】:

    标签: elasticsearch elasticsearch-aggregation


    【解决方案1】:

    TLDR;

    某些类型溜进了您的代码。 我希望我已经修复了它。

    GET /so_agg_painless/_search
    {
      "size":15,
      "aggs":{
        "sum_the_hard_way": {
          "scripted_metric": {
            "init_script": {
              "source": """
                state.values = [];
                state.timestamps = [];
              """
            },
            "map_script": {
              "source": """
                state.values.add(doc['value'].value);
                state.timestamps.add(doc['timestamp'].value);
              """
            },
            "combine_script": {
              "source": """
                def rates = [];
                for ( int i = 0; i <= state.values.size()-2 ; i++ ) {
                  def nom = (state.values[i+1]- state.values[i]);
                  def denom = (state.timestamps[i+1]- state.timestamps[i]);
                  rates.add(nom/denom);
                } 
                return rates
                """
            },
            "reduce_script": {
              "source": """
                def vals = [];
                for (a in states) { 
                  vals.add(a) 
                }
                return vals
                """
            }
          }
        }
      }
    }
    

    嘿伙计,你的代码中有很多错别字,这就是它失败的原因。 但我认为逻辑很完美,所以对你表示敬意,所以非常接近。

    您需要注意代码中的那些s

    您也可以在我发布的代码中看到。使用"""。所以你可以缩进代码,这样更容易阅读和修复。

    【讨论】:

    • 嘿伙计,非常感谢!它现在工作得很好!谢谢你的好建议,我会坚持下去!
    • 我很高兴它有帮助!玩得开心
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多