2014-02-20 73 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() 
相關問題