首页 > 解决方案 > 实体的属性可以是 Google Cloud Datastore 中的另一个实体吗?

问题描述

这是它在文档中所说的:

数据存储模式支持属性值的多种数据类型。其中包括:

整数

浮点

数字

字符串

日期

二进制数据

是否可以将不同类型的实体分配为 Google Cloud Datastore 中另一个实体的属性?

标签: google-cloud-platformnosqlgoogle-cloud-datastoreentity

解决方案


所以你想将一个实体嵌套在另一个实体中?

python ORMndb有一个叫做属性类型的东西ndb.StructuredProperty()

https://cloud.google.com/appengine/docs/standard/python/ndb/entity-property-reference#structured

class Address(ndb.Model):
    type = ndb.StringProperty()  # E.g., 'home', 'work'
    street = ndb.StringProperty()
    city = ndb.StringProperty()

class Contact(ndb.Model):
    name = ndb.StringProperty()
    addresses = ndb.StructuredProperty(Address, repeated=True)

guido = Contact(
    name='Guido',
    addresses=[
        Address(
            type='home',
            city='Amsterdam'),
        Address(
            type='work',
            street='Spear St',
            city='SF')])

但这只是 ORM 的伎俩。它实际上存储为:

name = 'Guido'
addresses.type = ['home', 'work']
addresses.city = ['Amsterdam', 'SF']
addresses.street = [None, 'Spear St']

数组是重复实体的存储方式: https ://cloud.google.com/appengine/docs/standard/python/ndb/entity-property-reference#repeated

编辑:

所以我刚刚从你那里注意到你正在使用 Python3,它使用了这个库https://googleapis.github.io/google-cloud-python/latest/datastore/index.html

不幸的是,该库的功能远不如ndb. 他们正在努力移植ndb到 python3,但它仍处于 alpha 阶段https://github.com/googleapis/python-ndb

但是,您仍然可以尝试以相同的方式保存ndb

from google.cloud import datastore
client = datastore.Client()
key = client.key('Contact', 1234)
entity = datastore.Entity(key=key)
entity.update({
    'name': Guido',
    'addresses.type': ['home', 'work'],
    'addresses.city' = ['Amsterdam', 'SF']
    'addresses.street' = [None, 'Spear St']
})

我不确定工作的唯一部分是发送重复属性的数组


推荐阅读