Search code examples
elasticsearchelastic-stack

I want to sort my elastic search aggregation data with most recent login for each user by there name


I want to create a query for elastic search where I get data for each user with there latest login time, and they must sort by there username, I want each user not multiple data of each user, I'm able to create the query using agg but right now I'm stuck at out sort on buckets based on username or any other field.

GET /login_history/_search
{
  "size": 0,
  "query": {
    "bool": {
   "must": [
    {
     "query_string": {
      "fields": [
       "username",
       "fullname"
      ],
      "query": "\"ayan\""
     }
    }
   ]
  }
  },
  "aggs": {
    "total_count": {
      "cardinality": {
        "field": "userid"
      }
    },
    "group_by_userId": {
      "terms": {
        "field": "userid",
        "size": 3,
        "include": {
          "partition": 0,
          "num_partitions": 2
        }
      },
      "aggs": {
        "latest_login": {
          "top_hits": {
             "_source": {
         "includes": ["username", "userid","logintime",]
       }, 
            "sort": [
              {
                "logintime": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}

Solution

  • Okay, I got the ans from elastic search team. It's not possible - github