Is there a way to interleave (round-robin) search results in Elasticsearch?

Hi Elasticsearch team and community,

I’m working on a app where I need to:

  • Sort products primarily by a priority field (priority), descending.
  • But also interleave (round-robin) results from different groups, so that no two consecutive products come from the same group.
  • Ideally, the interleaving respects the weighted priority of products (higher priority groups appear more frequently but results are still mixed).
  • Support pagination (e.g., 24 results per page).

For example, if I have groups with priorities:

  • GROUP A: 20
  • GROUP B: 20
  • GROUP C: 20
  • GROUP D: 1

I want results like:
[GROUP A Product 1, GROUP B Product 1, GROUP C Product 1, GROUP A Product 2, GROUP B Product 2, ...]

I have explored:

  • Sorting by priority — works but groups groups together, causing consecutive items from the same group.

Is there any native or recommended way to achieve this kind of weighted round-robin or interleaving within Elasticsearch’s query or sorting capabilities?

If not, are there best practices or patterns to implement this efficiently, maybe combining ES with application-side logic?

Thanks in advance!

Welcome!

I’m wondering if you should use something like a terms agg by group and then a top_hits for each group.

Something like:

POST /sales/_search?size=0
{
  "aggs": {
    "top_tags": {
      "terms": {
        "field": "group",
        "size": 4
      },
      "aggs": {
        "top_hits_per_group": {
          "top_hits": {
            "size": 24
          }
        }
      }
    }
  }
}

Then may be solve the rest of your business case on the application side.

Would that work?