2020-08-31 18:00:00+00:00

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.

Leveraging NDB In-Context & Memcache Auto-Batching

Always fetch related entities via ndb.get_multi() rather than sequential key.get() loops so NDB coalesces Memcache and Datastore RPCs into a single network round-trip.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs