0

is it possible to have aggregations with a random order? It seems that there is only asc or desc possible?

{
"aggs" : {
    "genders" : {
        "terms" : {
            "field" : "gender",
            "order" : { 
                "_count" : "asc" 
                }
            }
        }
    }
}
Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
user2409399
  • 257
  • 2
  • 16

3 Answers3

2

Yes it is possible. Did it this way:

{
  "aggs": {
    "genders": {
      "terms": {
        "field": "gender",
        "size": 10,
        "order": {
          "rnd.max": "asc"
        }
      },
      "aggs": {
        "rnd": {
          "stats": {
            "script": "Math.random()"
          }
        }
      }
    }
  }
}

I'm using the stats-aggregation here as my random-number-generator, as it has a script-property, but any other metrics-aggregation with a script-property should do it also. You can play with the size-property of the terms-aggregation to control the number of buckets returned. The smaller the value is, the faster the aggregation runs.

1

Nope, according to the official documentation, terms aggregations are always sorted one way or another. If not specified, aggregated terms are sorted by count descending.

If at all needed, you can always shuffle the results on the client-side in some random order, though.

Val
  • 207,596
  • 13
  • 358
  • 360
1

Yes you can show random results refer to the answer provided here:
Random order & pagination Elasticsearch

You can try something like this. I wanted to randomize the results inside buckets so I have used it.

{
  "aggs": {
    "genders": {
      "terms": {
        "field": "gender"
      },
      "aggs": {
        "search_second": {
          "top_hits": {
            "sort": {
              "_script": {
                "script": "Math.random()",
                "type": "number",
                "params": {},
                "order": "asc"
              }
            }
          }
        }
      }
    }
  }
} 
Community
  • 1
  • 1
Nakul91
  • 1,245
  • 13
  • 30
  • Hello, Nakul91! I am not sure that your answer answers the question directly. It was asked how to order terms aggregation buckets randomly, but in your answer you show how to sort the inner hits inside a bucket. Those are different things. – Sergii Golubev Jul 24 '17 at 11:06