Search code examples
google-cloud-platformnosqlgoogle-cloud-datastoreentity

Can the property of an entity be another entity in Google Cloud Datastore?


Here's what it says in the documentation:

Datastore mode supports a variety of data types for property values. These include, among others:

Integers

Floating-point

numbers

Strings

Dates

Binary data

Is it possible to assign an entity of a different type as a property of another entity in Google Cloud Datastore?


Solution

  • So you want to nest one entity inside of an another entity?

    The python ORM ndb has something called the property type 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')])
    

    But this just trick that the ORM does. It actually gets stored as:

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

    The arrays are how repeated entities are stored: https://cloud.google.com/appengine/docs/standard/python/ndb/entity-property-reference#repeated

    EDIT:

    So I just noticed from you other question that you are using Python3 which uses this library https://googleapis.github.io/google-cloud-python/latest/datastore/index.html

    Unfortunately, that library is much less feature-ful than ndb. They are working on porting ndb over to python3, but it is still in alpha https://github.com/googleapis/python-ndb

    However you could still try to save it the same way that ndb does

    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']
    })
    

    The only part of this that I'm not sure with work is sending arrays for repeated properties