我正在尝试使用mongodb作为后端,在django中定义一个时序模型。我读过一些关于best practices for timeseries data at the MongoDB Blog的文章,我想我已经足够理解它了。但现在,我的问题是:如何使用django的模型语法定义这样的模型?我不确定它们是embedded documents还是简单地将arrays或dicts存储在模型字段中。以下是建议的mongo格式:
理想的mongo文档格式:
{
timestamp_hour: ISODate("2013-10-10T23:00:00.000Z"),
type: “memory_used”,
values: {
0: { 0: 999999, 1: 999999, …, 59: 1000000 },
1: { 0: 2000000, 1: 2000000, …, 59: 1000000 },
…,
58: { 0: 1600000, 1: 1200000, …, 59: 1100000 },
59: { 0: 1300000, 1: 1400000, …, 59: 1500000 }
}
}一种解决方案是这样做,一个文档保存一天的数据:
# models.py
class timeseries(models.Model):
date = models.DateField(null=True)
value_hour_0 = models.CharField(max_length='1024', blank=True)
value_hour_1 = models.CharField(max_length='1024', blank=True)
value_hour_...
value_hour_23 = models.CharField(max_length='1024', blank=True)即使我将arrays或dicts存储在value_hour_n字段中,它也不能提供本文中提到的查询文档的优点,例如查询为timeseries.HR.MIN。有什么建议吗?
发布于 2014-02-21 10:36:18
我完全不同意这种结构是一种理想的格式,我似乎总是看到这种符号被用来理解如何建模一个数组,但这并不适合Mongo的解释。
出于我更详细地介绍here的原因,我通常发现以下结构对于查询目的更灵活:
{
timestamp_hour: ISODate("2013-10-10T23:00:00.000Z"),
type: “memory_used”,
values: [
[ 999999, 999999, …, 1000000 ],
[ 2000000, 2000000, …, 1000000 ],
…,
[ 1600000, 1200000, …, 1100000 ],
[ 1300000, 1400000, …, 1500000 ]
]
}通过这种方式(如另一个答案中所解释的),您不需要专门寻址路径的任何部分来访问任何元素。子文档表示法是单向的,您必须完全指定每个表示法,不能做一系列的事情或在不同的位置查找值。
使用数组,你无论如何都会得到自由的位置符号,所以你可以values.59,甚至values.20.15,如果你想的话,或者在数组中匹配文档中的键。
对于您的解决方案,您需要更多地尝试,但这篇文章和其他阅读文章给出了一般的要点。
发布于 2014-02-21 17:38:10
你可以按照你写的那样做,但是如果你想每2小时或每30分钟存储一次值呢?所以这不是一个好的做法
这样如何:
class MyModelStat(models.Model):
#other fields like : nbr_views, nbr_clicks, rates ...
my_model = models.ForeignKey(MyModel, related_name="stats")
created_on = models.DateTimeField(auto_now_add=True)
previous = models.ForeignKey('self', blank=True, null=True, editable=False)
def save(self, **kwargs):
current_stats = self.my_model.current_stats
if current_stats is not None and self.id is None:
#iterate over the fields, and do your stuff
self.rates = current_stats.rates + 1
self.nbr_views = current_stats.nbr_views
#set the current stat as the previous for the new stat
self.previous = self.deal.current_stats
super(MyModelStat, self).save(**kwargs)
@receiver(post_save, sender=MyModelStat)
def set_mymodel_stats(sender, *args, **kwargs):
"""
Signal handler to ensure that a new stats is always chosen as the current stats - automatically. It simplifies stuff
greatly. Also stores previous revision for diff-purposes
"""
instance = kwargs['instance']
created = kwargs['created']
if created and instance.my_model:
instance.my_model.current_stats = instance
instance.my_model.save()https://stackoverflow.com/questions/21917974
复制相似问题