Make a slow aggregation fast, by measuring first
Your instinct about what is slow is usually wrong. You print the times before touching anything, and check afterward that the answer has not changed. You also find one rewrite that turns out to do nothing.