google-app-enginemaxindexed-properties

Finding the largest value of an indexed property in AppEngine


Let's say I have several entities stored in the AppEngine DataStore that all have an indexed numerical property and I need to find the largest currently existing value.

I could simply do a projection query sorted on this property with descending sort-order and a limit of 1. The returned result would then contain my answer.

Is this the best approach or is there a more efficient way to get this value?

(Consistency is not too much of a worry in this case. If I miss a couple values that are being committed simultaneously, I don't care too much. So, no need for transactions here.)


Solution

  • Since GAE datastore does not have an equivalent to MAX on an SQL database, it is indeed best to order by the column and retrieve the first entry. For example:

    max_val = MyEntity.query().order(-MyEntity.my_numeric_field).get().my_numeric_field
    

    See also this forum discussion.

    Your second option would be to store the maximum value in some other entity and then update it (probably in a transaction) whenever you add one of your first entities.