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

day*_*mer 3 python google-app-engine app-engine-ndb google-cloud-datastore

从App Engine NDB 文档:

NDB API在无模式对象数据存储区中提供持久存储.它支持自动缓存,复杂查询和原子事务.NDB非常适合存储结构化数据记录.

我想使用NDB创建如下所示的结构,其中每个实例如下所示:

{
 city: 'SFO'
 date: '2013-01-27'
 data: {
           'keyword1': count1,
           'keyword2': count2,
           'keyword3': count3,
           'keyword4': count4,
           'keyword5': count5,
           ....
       }
}
Run Code Online (Sandbox Code Playgroud)

如何使用NDB在Google App Engine(GAE)中设计这样的无模式实体?
我是GAE的新手,不知道如何实现这一目标

谢谢

DTi*_*ing 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,})
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

这里的问题是过滤结构化属性.关键字的属性被视为并行数组.进行如下查询:

q = MyModel.query(MyModel.data.keyword=='keyword1',
                  MyModel.data.count > 4)
Run Code Online (Sandbox Code Playgroud)

会错误地包含my_model.

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

使用expando模型可以使用并允许您查询关键字:

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) 
Run Code Online (Sandbox Code Playgroud)

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