Aggregation query: get value from the latest doc

I want to build a query to get the price from the latest document (time). And within the query, there can be other aggregations like “avg”.
The query will be like:

 "query" : {
    // some filters
    "aggregations" : {
           "AVG_price” : {
              "avg" : {
                    "field" : “price”
                 }
              },
               "LAST_price” : {
                  // get the price from the latest, i.e, "price" from the doc of max(“time”); how??
               }
      // snip   

Documents have fields like:

“price” : 100
“time” (epoch) : 1531332965000

What will be the best way to have “Last_price”?
We are using Elasitcsearch 5.6.4.
Thanks in advance.

Solved with a script. Let me know if you can think of a better solution (especially performance wise).

    "LAST_Price" : {
      "scripted_metric" : {
        "init_script" : {
          "source" : "params._agg.x=0; params._agg.y=\"\";",
          "lang" : "painless"
        },
        "map_script" : {
          "source" : "if (params['_source']['price'] != null) {if (params['_source']['time'] > params._agg.x) {params._agg.x=params['_source']['time'];params._agg.y=params['_source']['price'] }}",
          "lang" : "painless"
        },
        "combine_script" : {
          "source" : "return params._agg",
          "lang" : "painless"
        },
        "reduce_script" : {
          "source" : "long xx=0; String yy=\"\";for (tt in params._aggs) {if (tt.x>xx) {xx=tt.x; yy=tt.y}}return yy",
          "lang" : "painless"
        }
      }
    }

What about using a nested top_hits aggregation to return 1 document sorting by age descending.

Top_hits works for me; even though I need to work on different result output formats the performance is so much better than using scripts.
Thanks much!!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.