Depending on your situation, you may want to look at a plugin like datasweet, then you can do term query aggregations, and only do math on the client, rather than burden the server with a script for each doc. If that helps