I encountered a problem, as I need to sort my buckets using a keyword field for this I have tried two approaches.
- I have been trying to sort the result of my aggregation (buckets) from the top hit aggregation. My top_hits contains one element which is the username
"user_data": {
"top_hits": {
"_source": {
"includes": ["username"]
},
"size": 1
}
},
To sort the buckets i'm trying with a bucket sort, the bucket sort is something like this
sorting": {
"bucket_sort": {
"sort": [
{
"user_data>username": { ----> This is the error
"order": "desc"
}
}
],
"from": 0,
"size": 25
}
}
But I received a syntax error basically the bucket path is wrong.
- Another approach that I used to accomplish the sort was to add another aggregation over the username to obtain the max. Something like this
"to_sort" : {
"max": {
"field": "username"
}
}
And use the following bucket_sort
"sorting": {
"bucket_sort": {
"sort": [
{
"to_sort": {
"order": "desc"
}
}
],
"from": 0,
"size": 25
}
}
But basically I can't to use a keyword field to use the max aggregation. Is there a way to sort my buckets using the username, the username is a keyword field?
The parent of my aggregation is
"aggs": {
"CountryId": {
"terms": {
"field": "countryId",
"size": 10000
}
The value of the username is different between each bucket
The result of the buckets is something like this
"buckets" : [
{
"key" : "11111",
"doc_count" : 17,
"user_data" : {
"hits" : {
"total" : 10,
"max_score" : 11,
"hits" : [
{
"_index" : "index_name",
"_type" : "index_name",
"_id" : "101010",
"_score" : 0.0,
"_source" : {
"username" : "cccccc"
}
}
]
}
}
},
{
"key" : "33333",
"doc_count" : 17,
"user_data" : {
"hits" : {
"total" : 10,
"max_score" : 11,
"hits" : [
{
"_index" : "index_name",
"_type" : "index_name",
"_id" : "101010",
"_score" : 0.0,
"_source" : {
"username" : "bbbbb"
}
}
]
}
}
},
{
"key" : "22222",
"doc_count" : 17,
"user_data" : {
"hits" : {
"total" : 10,
"max_score" : 11,
"hits" : [
{
"_index" : "index_name",
"_type" : "index_name",
"_id" : "101010",
"_score" : 0.0,
"_source" : {
"username" : "aaaaa"
}
}
]
}
}
}
]
And the following buckets result is I would like to have
"buckets" : [
{
"key" : "22222",
"doc_count" : 17,
"user_data" : {
"hits" : {
"total" : 10,
"max_score" : 11,
"hits" : [
{
"_index" : "index_name",
"_type" : "index_name",
"_id" : "101010",
"_score" : 0.0,
"_source" : {
"username" : "aaaaa"
}
}
]
}
}
},
{
"key" : "33333",
"doc_count" : 17,
"user_data" : {
"hits" : {
"total" : 10,
"max_score" : 11,
"hits" : [
{
"_index" : "index_name",
"_type" : "index_name",
"_id" : "101010",
"_score" : 0.0,
"_source" : {
"username" : "bbbbb"
}
}
]
}
}
},
{
"key" : "11111",
"doc_count" : 17,
"user_data" : {
"hits" : {
"total" : 10,
"max_score" : 11,
"hits" : [
{
"_index" : "index_name",
"_type" : "index_name",
"_id" : "101010",
"_score" : 0.0,
"_source" : {
"username" : "ccccc"
}
}
]
}
}
}
]
How you can see the buckets was order by username.
username
value per bucket? – Val