2 minutes
Use @derivedFrom Instead of Growing Arrays
Arrays in your schema slow a Subgraph down as they grow beyond thousands of entries, because Graph Node copies the whole array on every update. Use the @derivedFrom directive for one-to-many relationships instead. It prevents large arrays from forming, simplifies handlers, and keeps entities small, which speeds up both indexing and queries.
How to Use the @derivedFrom Directive
Add a @derivedFrom directive after the array field in your schema:
1comments: [Comment!]! @derivedFrom(field: "post")@derivedFrom creates efficient one-to-many relationships, enabling an entity to dynamically associate with multiple related entities based on a field in the related entity. This approach removes the need for both sides of the relationship to store duplicate data, making the Subgraph more efficient.
Example Use Case for @derivedFrom
An example of a dynamically growing array is a blogging platform where a “Post” can have many “Comments”.
Start with two entities, Post and Comment. Without optimization, you might store the comments as an array on the post:
1type Post @entity {2 id: Bytes!3 title: String!4 content: String!5 comments: [Comment!]!6}78type Comment @entity {9 id: Bytes!10 content: String!11}This array stores the comment references on the Post side of the relationship, and the array grows with every new comment.
Here is the optimized version with @derivedFrom:
1type Post @entity {2 id: Bytes!3 title: String!4 content: String!5 comments: [Comment!]! @derivedFrom(field: "post")6}78type Comment @entity {9 id: Bytes!10 content: String!11 post: Post!12}With @derivedFrom, the schema stores the relationship only on the Comment side, as a single post field. The comments field on Post is computed at query time, so it never grows in storage.
This makes your Subgraph more efficient and gives you three capabilities:
- Query a
Postand see all of its comments. - Do a reverse lookup: query any
Commentand see which post it belongs to. - Use derived field loaders (
loadRelated()) to read virtual relationships in your mappings. Derived fields are read-only in mappings.
Learn More
- Best Practices in Subgraph Development: Avoiding Large Arrays: more strategies for avoiding large arrays.
- Guides & Best Practices overview: the full checklist and how this page fits with the rest of the section.