When modeling structured data inside Google App Engine's Cloud Datastore, developers use the NDB library to define entities. Unlike relational databases that use fixed columns, NDB supports Structured Properties and Local Structured Properties. These features allow developers to embed complex nested models directly inside a parent document, providing dynamic schema layouts while maintaining quick database lookups.
By using structured properties, you can store related records (like billing line items or sensor metadata) inside a single entity.
1. Defining Nested Models with StructuredProperty
We declare a nested class model and reference it inside our parent table definition:
# ndb_models.py
from google.cloud import ndb
class HardwareInterface(ndb.Model):
interface_name = ndb.StringProperty(required=True)
port = ndb.IntegerProperty(required=True)
status = ndb.StringProperty(default="active")
class GatewayConfig(ndb.Model):
gateway_id = ndb.StringProperty(required=True)
# Embed list of hardware interfaces
interfaces = ndb.StructuredProperty(HardwareInterface, repeated=True)
created_at = ndb.DateTimeProperty(auto_now_add=True)
2. Structured vs Local Structured Properties
Properties declared as StructuredProperty are fully indexed by Datastore, allowing you to run queries on child attributes (e.g., finding all gateways containing an active interface port). If indexing is not needed, using LocalStructuredProperty saves the child list as an encrypted binary blob, reducing database write costs.