2014-02-20 29 views
0

我想在django中使用mongodb作为后端定义一个时间序列模型。我读了一些best practices for timeseries data at the MongoDB Blog,我想我对它了解得很清楚。但是现在,我的问题是:如何使用django的模型语法定义这样的模型?我不确定这些是embedded documents,还是仅仅在模型字段中存储arraysdicts。这里是建议蒙戈格式:如何在django-mongodb引擎中构造时间序列模型

理想蒙戈文档格式:

{ 
    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) 

即使我在value_hour_n字段中存储arraysdicts,但它并不完全提供查询文档中提到的优点,例如timeseries.HR.MIN。有什么建议么?

回答

2

我就不一一列举了在结构上是一个理想的格式,我似乎总是看到这种符号的使用如何数组建模的PHP理解“,但这并不适应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如果你想,或者以其他方式在阵列在文档中的匹配键,

对于您的解决方案,您需要多玩一些,但这和其他阅读给出了一般要领。

0

你可以做你写的东西,但是如果你想每隔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()