'I want sum_char2cust and sum_cust2char only for top 20 document of user

GET chatsession/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "char2cust": {
              "gte": 10
            }
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "uniq_user": {
      "terms": {
        "field": "user_name",
        "size": 99999
      },
      "aggs": {
        "sum_char2cust": {
          "sum": {
            "field": "char2cust"
          }
        },
        "sum_cust2char": {
          "sum": {
            "field": "cust2char"
          }
        }
      }
    }
  }
}

I want sum_char2cust and sum_cust2char only for top 20 document of unique user. I have tried using top_hits and other solutions but not worked for me.



Solution 1:[1]

Below query should gives you expected result

GET chatsession/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "char2cust": {
              "gte": 10
            }
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "uniq_user": {
      "terms": {
        "field": "user_name",
        "size": 20         --> Note here.
      },
      "aggs": {
        "sum_char2cust": {
          "sum": {
            "field": "char2cust"
          }
        },
        "sum_cust2char": {
          "sum": {
            "field": "cust2char"
          }
        }
      }
    }
  }
}

Solution 2:[2]

In order to get the sum of char2cust and cust2char field, for top 20 users (based on their id), you need to sort the terms aggregation result based on the Max Aggregation result.

Try out this below query:

{
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "char2cust": {
                            "gte": 10
                        }
                    }
                }
            ]
        }
    },
    "size": 0,
    "aggs": {
        "uniq_user": {
            "terms": {
                "field": "user_name",
                "size": 20,
                "order": {
                    "latestOrder": "desc"
                }
            },
            "aggs": {
                "sum_char2cust": {
                    "sum": {
                        "field": "char2cust"
                    }
                },
                "sum_cust2char": {
                    "sum": {
                        "field": "cust2char"
                    }
                },
                "latestOrder": {
                    "max": {
                        "field": "id"
                    }
                }
            }
        }
    }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Amit
Solution 2 ESCoder