0

I've got the following ElasticSearch-query, to get 10 documents from each "category" grouped on "cat.id":

"aggs": {
    "test": {
        "terms": {
            "size": 10,
            "field": "cat.id"
        },
        "aggs": {
            "top_test_hits": {
                "top_hits": {
                    "_source": {
                        "includes": [
                            "id"
                        ]
                    },
                    "size": 10
                }
            }
        }
    }
}

This is working fine. However I cannot seem to find a way, to randomly take 10 results from each bucket. The results are always the same. And I would like to have 10 random items from each bucket. I tried all kinds of things which are intended for documents, but non of them seem to be working.

mhtsbt
  • 1,029
  • 2
  • 12
  • 26
  • Possible duplicate of [Elastic Search: aggregation random order?](https://stackoverflow.com/questions/30466664/elastic-search-aggregation-random-order) – Polynomial Proton Jun 19 '18 at 17:33

1 Answers1

0

As was already suggested in this answer, you can try using random sort in the top_hits aggregation, using a _script like this:

{
  "aggs": {
    "test": {
      "terms": {
        "size": 10,
        "field": "cat.id"
      },
      "aggs": {
        "top_test_hits": {
          "top_hits": {
            "_source": {
              "includes": [
                "id"
              ]
            },
            "size": 10,
            "sort": {
              "_script": {
                "type": "number",
                "script": {
                  "lang": "painless",
                  "source": "(System.currentTimeMillis() + doc['_id'].value).hashCode()"
                },
                "order": "asc"
              }
            }
          }
        }
      }
    }
  }
}

Random sorting was broadly covered in this question.

Hope that helps!

Nikolay Vasiliev
  • 5,656
  • 22
  • 31