如何从谷歌应用引擎返回按年龄分组的计数学生?

时间:2013-11-06 10:37:45

标签: python google-app-engine

我是Google App Engine的新手,我使用的是Python,我为学生创建了模型 有姓名和年份,我已存储记录。如何按年龄分组返回计数学生?

for example 
25 years old    12 students
18 years old    125 students

依旧......

from google.appengine.ext import ndb


class StudentModel(ndb.Model):
    name = ndb.StringProperty(indexed=True)
    age = ndb.IntegerProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)

3 个答案:

答案 0 :(得分:4)

您还可以先使用distinct=Truegroup_by=['age']来获取唯一年龄,然后将其视为异步。但是,对于大数据集来说,最好的方法是在每次放置的地方存储和更新这个数字。

ages = StudentModel.query(projection=['age'], distinct=True).fetch()

counts = {}
for age in ages:
  # query to get num of students for each age
  counts[age.age] = StudentModel.query(StudentModel.age == age.age).count_async()

# get result for each counter
for c in counts:
  counts[c] = counts[c].get_result()

for age in counts:
  print '%s years old \t %s students' % (age, counts[age])

答案 1 :(得分:3)

除非在添加实体时保持运行总计,否则您需要跨所有实体执行查询。最简单/最简单的方法是使用查询的map方法将年龄添加到collections.Counter http://docs.python.org/2/library/collections.html

from collection import Counter
c = Counter()

def count(x):
   c[x.age]+=1

result = StudentModel.query().map(count)

c是一个字典,其中包含所有年龄段的总和,其年龄是字典中的关键字。 result将包含None值列表,如果您希望result和count函数中的每个实体都返回x

如果您有大量实体/并尝试在前面的请求中执行此操作,则可能很容易花费很长时间并导致DeadlineExceededError。如果您的实体很大,那么投影查询可能会更快一些。

答案 2 :(得分:2)

上面的答案仅适用于非常小的数据集。对于大型数据集,您需要使用mapreduce之类的东西,否则您应该使用支持分组和聚合的云sql,而不是数据存储区。