Elastic Search: aggregation random order?

后端 未结 3 1231
借酒劲吻你
借酒劲吻你 2021-01-27 15:21

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

{
\"aggs\" : {
    \"genders\" : {
        \"terms\" :         


        
相关标签:
3条回答
  • 2021-01-27 15:33

    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.

    0 讨论(0)
  • 2021-01-27 15:39

    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.

    0 讨论(0)
  • 2021-01-27 15:56

    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"
                  }
                }
              }
            }
          }
        }
      }
    } 
    
    0 讨论(0)
提交回复
热议问题