'How to use result of one query in another query in Elasticsearch

Using Elasicsearch 7.9

Index

{
  "age": 5
}
{
  "age": 10
}
{
  "age": 11
}
{
  "age": 14
}
{
  "age": 21
}

I have to find median of the age from above index. What I did:

{
  "size": 0, 
  "aggs": {
    "median": {
      "percentiles": {
        "field": "age",
        "percents": 50
      }
    }
  }
}

Then I have to take the result and pass the median to search the age greater than median age.

{
  "query": {
    "range": {
      "age": {
        "gte": 11
      }
    }
  }
}

I can do like this. But I have to do it in one query. I am doing it from java rest client. For this simple operation using two queries seems to be not optimal.

Can I do it with single query? I thought I can do this with scripting. I am not getting how to achieve this.

Please help me. Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source