2 minutes
Podgraf Doporučený postup 2 - Zlepšení indexování a rychlosti dotazů pomocí @derivedFrom
TLDR
Arrays in your schema can really slow down a Subgraph’s performance as they grow beyond thousands of entries. If possible, the @derivedFrom
directive should be used when using arrays as it prevents large arrays from forming, simplifies handlers, and reduces the size of individual entities, improving indexing speed and query performance significantly.
Jak používat směrnici @derivedFrom
Stačí ve schématu za pole přidat směrnici @derivedFrom
. Takto:
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.
Příklad případu použití pro @derivedFrom
Příkladem dynamicky rostoucího pole je blogovací platforma, kde “příspěvek“ může mít mnoho “komentářů“.
Začněme s našimi dvěma entitami, příspěvek
a Komentář
Bez optimalizace byste to mohli implementovat takto pomocí pole:
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}
Taková pole budou efektivně ukládat další data komentářů na straně Post vztahu.
Zde vidíte, jak vypadá optimalizovaná verze s použitím @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}
Pouhým přidáním direktivy @derivedFrom
bude toto schéma ukládat “Komentáře“ pouze na straně “Komentáře“ vztahu a nikoli na straně “Příspěvek“ vztahu. Pole se ukládají napříč jednotlivými řádky, což umožňuje jejich výrazné rozšíření. To může vést k obzvláště velkým velikostem, pokud je jejich růst neomezený.
This will not only make our Subgraph more efficient, but it will also unlock three features:
-
Můžeme se zeptat na
Post
a zobrazit všechny jeho komentáře. -
Můžeme provést zpětné vyhledávání a dotazovat se na jakýkoli
Komentář
a zjistit, ze kterého příspěvku pochází. -
We can use Derived Field Loaders to unlock the ability to directly access and manipulate data from virtual relationships in our Subgraph mappings.
Závěr
Use the @derivedFrom
directive in Subgraphs to effectively manage dynamically growing arrays, enhancing indexing efficiency and data retrieval.
For a more detailed explanation of strategies to avoid large arrays, check out Kevin Jones’ blog: Best Practices in Subgraph Development: Avoiding Large Arrays.