2 минуты
Лучшая практика для субграфов 2 — улучшение индексирования и отклика на запросы с помощью @derivedFrom
Краткое содержание
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.
Как использовать директиву @derivedFrom
Вам нужно просто добавить директиву @derivedFrom после массива в своей схеме. Например:
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.
Пример использования @derivedFrom
Пример динамически растущего массива — это платформа для блогов, где у “Поста” может быть много “Комментариев”.
Начнем с наших двух объектов: Post
и Comment
Без оптимизации Вы могли бы реализовать это следующим образом, используя массив:
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}
Подобные массивы будут эффективно хранить дополнительные данные о Comments на стороне отношения Post.
Вот как будет выглядеть оптимизированная версия с использованием @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}
Именно при добавлении директивы @derivedFrom
, эта схема будет хранить “Comments” только на стороне отношения “Comments”, а не на стороне отношения “Post”. Массивы хранятся в отдельных строках, что позволяет им значительно расширяться. Это может привести к очень большим объёмам, поскольку их рост не ограничен.
This will not only make our Subgraph more efficient, but it will also unlock three features:
-
Мы можем запрашивать
Post
и видеть все его комментарии. -
Мы можем выполнить обратный поиск и запросить любой
Comment
, чтобы увидеть, от какого поста он пришел. -
We can use Derived Field Loaders to unlock the ability to directly access and manipulate data from virtual relationships in our Subgraph mappings.
Заключение
Use the @derivedFrom
directive in Subgraphs to effectively manage dynamically growing arrays, enhancing indexing efficiency and data retrieval.
Для более подробного объяснения стратегий, которые помогут избежать использования больших массивов, ознакомьтесь с блогом Кевина Джонса: Лучшие практики разработки субграфов: как избежать больших массивов.