A blog about one guys quest to learn Python, Django and Google App Engine.
Feed: http://appengineguy.com/atom.xml

den 16 juli 2008

How to do AVG and SUM in Google App Engine Data Store

People who are used to relational databases, which is pretty much every gosh-darned web developer out there, will run into pretty much the same obstacles with the app engine datastore - one of them is How the heck do I do SUM or AVG?. Yeah, due to how the Data Store works - you cannot do any kind of aggregate query. Instead, you have to re-calculate the totals at write time and keep them in a Counter instead. Like this:

models.py

And you use it like this...

tests.py

Performance note: It is a slightly bad idea to do counters like I have done above, but in my defence, I have done it for simplicity. In practice, it's important that you shard your counters.

As always, comments and questions are always welcome!

8 kommentarer:

Alex sa...

I don't understand why you need a custom Callable class -- wouldn't the built-in staticmethod (used as a decorator, @staticmethod) do just as well?

Mattias Johansson sa...

Well, what do you know! Looks lite it! I'll update the code later today using @staticmethod.

For some reason, I didn't find how to do static methods in python when googling - maybe I was on drugs at that particular moment in time.

davet sa...

Should line 42:
votes.save()
be
total.save()

asddsaadsdsa sa...

jaosro@netti.fi

asddsaadsdsa sa...

dsadsaadsdsa.wtfwtfwtf.asddsaa@gmail.com

Athar Shiraz Siddiqui sa...

May I ask how you are formatting your code so nicely? with alternating lines and line numbers; what are you using?

Calvin Spealman sa...

As pointed elsewhere, this global counter is itself a bottleneck. Instead, assume multiple counters by any name as shards and for the sum (or the sum that you then divide for an average) query for all of them and add up the total. This lets you grab multiple locks at the same time to update the same counter, because you update just one of many aggregate counters.

lord of rings sa...

Get More adds Earn Money