Sorting results not working properly

Hello,

I have a datastream that is updated often, I want to get unique results for the field @timestamp, I use this query:

GET datastream_name/_search
{        
    "sort" : [
    { "@timestamp" : {
      "order":"desc"
    }}
  ],
   "query": {
      "match": {
        "field.keyword": "fieldvaluie"
      }
    },
  
    "size": 0,
    "aggs" : {
      "langs" : {
        "terms" : { "field" : "@timestamp",  "size" : 500 }
      }                                                                                                               
    }
}             

I get this result:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 10000,
      "relation": "gte"
    },
    "max_score": null,
    "hits": []
  },
  "aggregations": {
    "langs": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 1699387356000,
          "key_as_string": "2023-11-07T20:02:36.000Z",
          "doc_count": 222108
        },
        {
          "key": 1699383777000,
          "key_as_string": "2023-11-07T19:02:57.000Z",
          "doc_count": 222043
        },
        {
          "key": 1699380171000,
          "key_as_string": "2023-11-07T18:02:51.000Z",
          "doc_count": 221973
        },
        {
          "key": 1699376574000,
          "key_as_string": "2023-11-07T17:02:54.000Z",
          "doc_count": 221958
        },
        {
          "key": 1699488183000,
          "key_as_string": "2023-11-09T00:03:03.000Z",
          "doc_count": 221739
        },```

As you can see is not sorted, it is important to mention that the field @timestamp was not initially in the mappings, so I followed the doc: https://www.elastic.co/guide/en/elasticsearch/reference/7.17/data-streams-change-mappings-and-settings.html#add-new-field-mapping-to-a-data-stream

So basically I changes the mappings in the configuration of the index_template and updating the mapping(step 2 in the document) but still I receive the same not sorted result.

Any help would be really appreciated.
Thanks.

EDIT Sorry I missread the Original Post...

@Mubolio

You are sorting in the wrong place you need to sort in the terms agg

1 Like

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