Docs
Поиск⌘ K
  • Главная страница
  • О The Graph
  • Поддерживаемые сети
  • Protocol Contracts
  • Субграфы
    • Субпотоки
      • Token API
        • AI Suite
          • Индексирование
            • Ресурсы
              Субграфы > Лучшие практики

              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:

              1. Мы можем запрашивать Post и видеть все его комментарии.

              2. Мы можем выполнить обратный поиск и запросить любой Comment, чтобы увидеть, от какого поста он пришел.

              3. 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.

              Для более подробного объяснения стратегий, которые помогут избежать использования больших массивов, ознакомьтесь с блогом Кевина Джонса: Лучшие практики разработки субграфов: как избежать больших массивов.

              Лучшие практики для субграфов 1-6

              1. Improve Query Speed with Subgraph Pruning

              2. Improve Indexing and Query Responsiveness by Using @derivedFrom

              3. Improve Indexing and Query Performance by Using Immutable Entities and Bytes as IDs

              4. Improve Indexing Speed by Avoiding eth_calls

              5. Simplify and Optimize with Timeseries and Aggregations

              6. Use Grafting for Quick Hotfix Deployment

              ⁠Редактировать на GitHub⁠

              Pruning with indexerHintsImmutable Entities and Bytes as IDs
              На этой странице
              • Краткое содержание
              • Как использовать директиву @derivedFrom
              • Пример использования @derivedFrom
              • Заключение
              • Лучшие практики для субграфов 1-6
              The GraphСтатусТестовая сетьБрундовые ресурсыФорумБезопасностьПолитика конфиденциальностиУсловия обслуживания