Home > front end >  I want sum_char2cust and sum_cust2char only for top 20 document of user
I want sum_char2cust and sum_cust2char only for top 20 document of user

Time:05-24

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.

CodePudding user response:

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"
          }
        }
      }
    }
  }
}

CodePudding user response:

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"
                    }
                }
            }
        }
    }
}
  • Related