Google App Engine NDB:如何存储文档结构?

3 投票
2 回答
5902 浏览
提问于 2025-04-17 13:48

来自App Engine NDB的文档

NDB API提供了一种无模式的对象数据存储,能够持久保存数据。它支持自动缓存、复杂查询和原子事务。NDB非常适合存储结构化的数据记录。

我想用NDB创建一个像下面这样的结构,每个实例看起来像:

{
 city: 'SFO'
 date: '2013-01-27'
 data: {
           'keyword1': count1,
           'keyword2': count2,
           'keyword3': count3,
           'keyword4': count4,
           'keyword5': count5,
           ....
       }
}

我该如何在Google App Engine(GAE)中使用NDB设计这样一个无模式的实体呢?
我对GAE还很陌生,不太确定该怎么做。

谢谢

2 个回答

2

你可以使用 ndb.JsonProperty 来在你的模型中表示一个列表、一个字典或者一个字符串。如果想了解更多信息,可以查看 这份文档

8

如果你不需要在数据中查询属性,可以使用@voscausa提到的其中一个属性:

JsonProperty

class MyModel(ndb.Model):
  city = ndb.StringProperty()
  date = ndb.DateProperty()
  data = ndb.JsonProperty()

my_model = MyModel(city="somewhere", 
                   date=datetime.date.today(),
                   data={'keyword1': 3,
                         'keyword2': 5,
                         'keyword3': 1,})

StructuredProperty:

class Data(ndb.Model):
  keyword = ndb.StringProperty()
  count = ndb.IntegerProperty()

class MyModel(ndb.Model):
  city = ndb.StringProperty()
  date = ndb.DateProperty()
  data = ndb.StructuredProperty(Data, repeated=True)

my_model = MyModel(city="somewhere", 
                   date=datetime.date.today(),
                   data=[Data(keyword="keyword1", count=3),
                         Data(keyword="keyword2", count=5),
                         Data(keyword="keyword3", count=1)])
my_model.put()

这里的问题是如何过滤结构化属性。Keyword的属性被视为并行数组。进行这样的查询:

q = MyModel.query(MyModel.data.keyword=='keyword1',
                  MyModel.data.count > 4)

会错误地包含my_model

https://developers.google.com/appengine/docs/python/ndb/queries#filtering_structured_properties

使用扩展模型(expando model)会有效,并且允许你查询关键词:

class MyModel(ndb.Expando):
  city = ndb.StringProperty()
  date = ndb.DateProperty()

m = MyModel(city="Somewhere", date=datetime.date.today())
m.keyword1 = 3
m.keyword2 = 5
m.keyword3 = 1
m.put()

q = MyModel.query(ndb.GenericProperty('keyword1') > 2) 

https://developers.google.com/appengine/docs/python/ndb/entities#expando

撰写回答