Skip to main content
 首页 » 编程设计

python之从导航台数据存储聚合数据的最佳方式

2025年05月04日10落叶无声

我有一个 StatisticStore 模型定义为:

class StatisticStore(ndb.Model): 
  user = ndb.KeyProperty(kind=User) 
  created = ndb.DateTimeProperty(auto_now_add=True) 
  kind = ndb.StringProperty() 
  properties = ndb.PickleProperty() 
 
  @classmethod 
  def top_links(cls, user, start_date, end_date): 
    ''' 
    returns the user's top links for the given date range 
    e.g. 
    {'http://stackoverflow.com': 30, 
     'http://google.com': 10, 
     'http://yahoo.com': 15} 
    ''' 
    stats = cls.query( 
      cls.user == user.key, 
      cls.created >= start_date, 
      cls.created <= end_date, 
      cls.kind == 'link_visited' 
    ) 
    links_dict = {} 
    # generate links_dict from stats 
    # keys are from the 'properties' property 
    return links_dict 

我想要一个 AggregateStatisticStore 模型,每天存储 StatisticStore 的聚合。它可以每天生成一次。像这样的东西:

class AggregateStatisticStore(ndb.Model): 
  user = ndb.KeyProperty(kind=User) 
  date = ndb.DateProperty() 
  kinds_count = ndb.PickleProperty() 
  top_links = ndb.PickleProperty() 

因此以下内容为真:

start = datetime.datetime(2013, 8, 22, 0, 0, 0) 
end = datetime.datetime(2013, 8, 22, 23, 59, 59) 
 
aug22stats = StatisticStore.query( 
  StatisticStore.user == user, 
  StatisticStore.kind == 'link_visited', 
  StatisticStore.created >= start, 
  StatisticStore.created <= end 
).count() 
aug22toplinks = StatisticStore.top_links(user, start, end) 
 
aggregated_aug22stats = AggregateStatisticStore.query( 
  AggregateStatisticStore.user == user, 
  AggregateStatisticStore.date == start.date() 
) 
 
aug22stats == aggregated_aug22stats.kinds_count['link_visited'] 
aug22toplinks == aggregated_aug22stats.top_links 

我正在考虑使用任务队列 API 运行一个 cronjob。该任务将生成每天的 AggregateStatisticStore。但我担心它可能会遇到内存问题?因为 StatisticStore 每个用户可能有很多记录。

此外,top_links 属性使事情有点复杂。我不确定在聚合模型中拥有它的属性是否是最好的方法。对该属性的任何建议都会很棒。

最终,我只想为 StatisticStore 保留大约 30 天前的记录。如果记录超过 30 天,则应将其汇总(然后删除)。节省空间并缩短可视化查询时间。

编辑 每次记录 StatisticStore 时,它会创建/更新相应的 AggregateStatisticStore 记录。这样,cronjob 所要做的就是清理。想法?

请您参考如下方法:

是的,mapreduce 对此很有帮助。或者,您可以使用“后端”(现在是模块)实例运行您的 cron 作业。这可以减轻内存问题和作业长度问题。

另一种方法可能是将聚合移动到写入时间。由于这是针对每个用户的,您可能会发现这样可以减少很多工作。 如果 AggregateStatisticStore 是每天,您可能希望使用 DateProperty 以外的其他日期。 DateProperty 当然可以工作,但我发现将 In​​tegerProperty 用于这种 int 只是“某天以来的某天”的事情更容易。