ELASTICSEARCH - Sort agg values only in most recent document

I want to return the most recent document of all results of the aggregations, but it is returning all the documents How can I solve that?

{
  "aggs": {
    "nested": {
      "nested": {
        "path": "data.add"
      },
      "aggs": {
        "desc": {
          "terms": {
            "field": "data.add.desc.keyword"
          },
          "aggs": {
            "nested": {
              "nested": {
                "path": "data.add.services"
              },
              "aggs": {
                "mobilephone": {
                  "filter": {
                    "term": {
                      "data.add.services.mobilephone": "true"
                    }
                  },
                  "aggs": {
                    "street": {
                      "cardinality": {
                        "field": "data.add.services.street.keyword"
                      }
                    },
                    "range":{
                      "top_hits": {
                        "size": 1,
                        "sort": [
                          {"created_at.keyword": {"order": "desc"}}]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Try adding a top hits aggregation, based off the timestamp.

For this case the solution is to add:

"order": {
          "_key": "desc":

instead of top_hits.

QUERY

{"size": 0, 
  "aggs": {
    "filtrofecha": {
      "terms": {
        "field": "created_at.keyword",
        "order": {
          "_key": "desc"
        },
        "size": 1
      },
      "aggs": {
        "nested": {
          "nested": {
            "path": "data.addresses"
              },
              "aggs": {
                "nested": {
                  "nested": {
                    "path": "data.addresses.services"
                  },
                  "aggs": {
                    "filter": {
                      "filter": {
                        "term": {
                          "data.addresses.services.field1.keyword": "true"
                        }
                      },
                      "aggs": {
                        "unique": {
                          "cardinality": {
                            "field": "data.addresses.services.field2.keyword"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

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