python - 谷歌应用引擎 NDB : How to store document structure?

标签 python google-app-engine google-cloud-datastore app-engine-ndb

来自 App Engine NDB documentation :

The NDB API provides persistent storage in a schemaless object datastore. It supports automatic caching, sophisticated queries, and atomic transactions. NDB is well-suited to storing structured data records.

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

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

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

谢谢

最佳答案

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

Json属性

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,})

结构化属性:

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

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

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 模型会起作用并允许您查询关键字:

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

关于python - 谷歌应用引擎 NDB : How to store document structure?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544834/

相关文章:

google-app-engine - 使用 get_by_key_name 从 GAE 数据存储中提取一个字段是否正确?

java - Google AppEngine (Java) 中的复杂类层次结构

python urllib.request - 可能有效的 header

python - 从 Python 中的 unicode 字符串中删除 HTML 标签

eclipse - Maven多模块项目,为什么需要 "pom packaging"?

Python:为什么这段代码会永远(无限循环?)

node.js - 如何使用 Node 设置和接收 Google Datastore 中的实体数据

python - Pandas : create plot

Python:产量和产量分配

java - 如何删除 Google App Engine (Java) 中的索引?