Aggregation on latest n records

Hi

Is there any way to do aggregation on latest N records?

this solution didn't work

{
   "query": {...},
   "size": N,
   "order": ...,
   "aggs": {
       ....
   }
}

for more detail: I want to get last 10 records from my records where "service_name" field is "x" and then aggregate on these 10 records to find out how many of these records have "success" in "resp_code" field.

my data is something like this:

[
  {
    "_index": "logs",
    "_type": "_doc",
    "_id": "1232525",
    "_score": 1,
    "_source": {
      "resp_body": "",
      "client_ip": "127.0.0.1",
      "resp_time": "2021-04-15T10:24:51+01:00",
      "@timestamp": "2021-04-15T05:55:00.452Z",
      "resp_code": "412",
      "service_name": "service1",
      "log_id": "1232525"
    }
  },
  {
    "_index": "logs",
    "_type": "_doc",
    "_id": "1232524",
    "_score": 1,
    "_source": {
      "resp_body": "",
      "client_ip": "127.0.0.1",
      "resp_time": "2021-04-15T10:23:51+01:00",
      "@timestamp": "2021-04-15T05:53:00.452Z",
      "resp_code": "0",
      "service_name": "service2",
      "log_id": "1232524"
    }
  },
  {
    "_index": "logs",
    "_type": "_doc",
    "_id": "1232523",
    "_score": 1,
    "_source": {
      "resp_body": "",
      "client_ip": "127.0.0.1",
      "resp_time": "2021-04-15T10:22:51+01:00",
      "@timestamp": "2021-04-15T05:52:00.452Z",
      "resp_code": "0",
      "service_name": "service1",
      "log_id": "1232523"
    }
  },
  {
    "_index": "logs",
    "_type": "_doc",
    "_id": "1232522",
    "_score": 1,
    "_source": {
      "resp_body": "",
      "client_ip": "127.0.0.1",
      "resp_time": "2021-04-15T10:21:51+01:00",
      "@timestamp": "2021-04-15T05:51:00.452Z",
      "resp_code": "0",
      "service_name": "service1",
      "log_id": "1232522"
    }
  },
  {
    "_index": "logs",
    "_type": "_doc",
    "_id": "1232521",
    "_score": 1,
    "_source": {
      "resp_body": "",
      "client_ip": "127.0.0.1",
      "resp_time": "2021-04-15T10:20:51+01:00",
      "@timestamp": "2021-04-15T05:50:00.452Z",
      "resp_code": "0",
      "service_name": "service2",
      "log_id": "1232521"
    }
  }
]

for example: I want to get last 2 records with "service_name=service1" and find how many records of those have "resp_code=0"

Welcome!

I'm not sure you can do that. That being said, it should be easy to compute this on the client side as you just have to iterate over the hits.

Hi David!

Thanks