is it possible accessing document's field returned from top hits aggregation?
i need sorting by default score in top hits sorting, and ordering the bucket from the root aggs by some other fields returned from top hits.
for example:
"aggregations": {
"spu_group": {
"aggregations": {
"sku_info": {
"top_hits": {
"_source": {
"include": "sku_id",
"include": "amount"
},
"size": 1
}
}
},
"terms": {
"field": "product_id",
"order": {
"sku_info.amount": "desc"
},
"size": 12
}
}
}
here i try to use "sku_info.amount" ordering the terms aggs of ”product_id“
Describe the feature:
Something like this is possible, but not direct with the top_hits aggregation. You need to use an additional metric agg and tell the terms agg to sort by that:
"aggregations": {
"spu_group": {
"aggregations": {
"sku_info": {
"top_hits": {
"_source": {
"include": "sku_id",
"include": "amount"
},
"size": 1
},
"top_hit" : {
"max": {
"field": "amount"
}
}
}
},
"terms": {
"field": "product_id",
"order": {
"top_hit": "desc"
},
"size": 12
}
}
}
this is what i do now.
the spu returned are different from the max amount and the top_hits
i may have three sku: s1 s2 s3.
top_hits return s2,
max amount return s1,
at last, the s2 shows up with order ordered by s1's amount.
@q11112345 Yes, that makes sense. The top_hits agg sorts by score while the max agg selects the max based on the amount field. If you change the max agg to the highest score then I think things should work like you want it to be:
"top_hit" : {
"max": {
"script": "_score"
}
}
Looks like there's nothing more to do here. Closing
@martijnvg thanks very much.
i do have problem.
my problem is :
1 pick up one doc from bucket by sorting by one field in top-hits, for example: pick up the doc with max score in bucket.
"top_hits" : {
"_source": {
"include": "sku_id",
"include": "amount"
},
"size": 1
}
2 then, sorting all buckets by another field of the doc which is picked up in "top_hits"
here i need sort buckets by doc field. and the field must be obtained from the top_hits.
i cant find a way to make this work.
there is no way to use the field returned from top_hits as i know .
may i post this problem again?
I have a problem with sorting aggregations on top fields.
aggs: { salary: {ranges: salary_ranges, score: 1}, company: {}, max_age: {ranges: age_ranges}, show_only: {order: {"_term" => "desc"}}, location: {}}
After the search I got sorting order are: 1. Max Age, 2. Show only, 3. Company, 4. Location, 5. Salary.
But I need the sorting order are: 1. Show only, 2. Location, 3. Salary, 4. Max age, 5. Company.
Most helpful comment
Something like this is possible, but not direct with the
top_hitsaggregation. You need to use an additional metric agg and tell the terms agg to sort by that: