diff --git a/src/server/search/aggregator.cc b/src/server/search/aggregator.cc index f36f64ec5c87..3547ed1622bc 100644 --- a/src/server/search/aggregator.cc +++ b/src/server/search/aggregator.cc @@ -66,16 +66,24 @@ void Aggregator::DoGroup(absl::Span fields, absl::Spansecond < it2->second); - }); - - if (descending) { - std::reverse(result.values.begin(), result.values.end()); - } + auto comparator = [&](const DocValues& l, const DocValues& r) { + auto l_it = l.find(field); + auto r_it = r.find(field); + + // Handle cases where one of the fields is missing + if (l_it == l.end() || r_it == r.end()) { + return l_it != l.end() || r_it == r.end(); + } + if (l_it->second < r_it->second) { + return !descending; + } + if (l_it->second > r_it->second) { + return descending; + } + return true; // Elements are equal + }; + + std::sort(result.values.begin(), result.values.end(), std::move(comparator)); result.fields_to_print.insert(field); }