0

我对 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)
4

3 回答 3

4

您也可以先使用distinct=Trueorgroup_by=['age']获取唯一的年龄,然后再对它们进行异步计数。但是对于大数据集,最好的方法是在每次 put 的某个地方存储和更新这个数字。

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])
于 2013-11-06T15:09:01.417 回答
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 值列表,如果您希望结果中的每个实体以及 count 函数将返回x.

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

于 2013-11-06T11:34:54.383 回答
2

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

于 2013-11-06T12:44:04.507 回答