GAE ndb 建立物件關聯的兩種方法

https://cloud.google.com/appengine/docs/python/ndb/queries#ancestor


今天因故有機會研究一下,發現建立物件關聯有兩種方式,各有利弊:

class Customer(ndb.Model):
    name = ndb.StringProperty()
class Purchase(ndb.Model):
    customer = ndb.KeyProperty(kind=Customer)
    price = ndb.IntegerProperty

上例中 Purchase 物件有個 customer 欄位,指向對應的 Customer 物件,假設是多個Purchase 對應到一個Customer 的關係,要查詢對應到特定 Customer 的 Purchase,執行以下查詢:

Purchase.query(customer=customer_entity.key).fetch()

利用上述作法的好處是資料的I/O 量不受限制,也就是說瞬時可以寫入多筆 Purchase,但並不保證資料的一致性,亦即有可能會查詢到還沒更新的資料。


另一種建立關聯的方式稱為建立 ancestor 鏈,即替每個 Purchase 物件指定父節點,作法如下:

class Customer(ndb.Model):
    name = ndb.StringProperty()
class Purchase(ndb.Model):
    price = ndb.IntegerProperty
注意到 Purchase 物件不必再指定 KeyProperty 欄位,取而代之的是在物件建立時替它指定 parnent(指向 parent 物件的 key):

purchase1 = Purchase(parent=customer_entity.key)
要查詢指到這個 parent 的所有 Purchase 即執行下列查詢(ancestor 查詢):

Purchase.query(ancestor=customer_entity.key).fetch()
這種做法的好處是確保同一個 ancestor group 裡面的資料絕對是一致的,但缺點是有每秒鐘只能寫入一次的限制。

留言

熱門文章