How to define percentage of result items with specific field in Elasticsearch query?

Viewed 105

I have a search query that returns all items matching users that have type manager or lead.

{
  "from": 0,
  "size": 20,
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "type": ["manager", "lead"]
          }
        }
      ]
    }
  }
}

Is there a way to define what percentage of the results should be of type "manager"?

In other words, I want the results to have 80% of users with type manager and 20% with type lead.

1 Answers

I want to make a suggestion to use bucket_path aggregation. As I know this aggregation needs to be run in sub-aggs of a histogram aggregation. As you have such field in your mapping so I think this query should work for you:

{
  "size": 0,
  "aggs": {
    "NAME": {
      "date_histogram": {
        "field": "my_datetime",
        "interval": "month"
      }, 
      "aggs": {
        "role_type": {
          "terms": {
            "field": "type",
            "size": 10
          },
          "aggs": {
            "count": {
              "value_count": {
                "field": "_id"
              }
            }
          }
        },
        "role_1_ratio": {
          "bucket_script": {
            "buckets_path": {
              "role_1": "role_type['manager']>count",
              "role_2": "role_type['lead']>count"
            },
            "script": "params.role_1 / (params.role_1+params.role_2)*100"
          }
        },
        "role_2_ratio": {
          "bucket_script": {
            "buckets_path": {
              "role_1": "role_type['manager']>count",
              "role_2": "role_type['lead']>count"
            },
            "script": "params.role_2 / (params.role_1+params.role_2)*100"
          }
        }
      }
    }
  }
}

Please let me know if it didn't work well for you.

Related