在GraphQL中考虑N+1的问题

我认为在Rails中使用GraphQL需要使用以下的宝石:
https://github.com/rmosolgo/graphql-ruby

使用GraphQL时容易出现N+1问题。因此考虑了以下代码。

module ShopsResolver
  def self.call(obj, args, ctx)
    limit    = args[:limit]
    order    = args[:order]
    bookable = args[:bookable]

    shops = Shop.visible
    shops = shops.limit(limit)              if limit.present?
    shops = shops.order('RAND()')           if order == "TRENDING" # 仮実装
    shops = shops.order('RAND()')           if order == "RANKING"  # 仮実装
    shops = shops.where(bookable: bookable) if bookable.present?

    shops = shops.includes(:area)
    shops = shops.includes(:categories)
    shops = shops.includes(:shop_categories)
    shops = shops.includes(:category_subs)
    shops = shops.includes(:shop_category_subs)
    shops = shops.includes(:situations)

    shops
  end
end

如果过度使用includes,会导致产生不必要的SQL查询,这是不好的。因此,我进行了防范措施的搜索。

    • Q: Prevent N+1 queries · Issue #189 · rmosolgo/graphql-ruby

 

    Pre-loading/Eager loading nested associations · Issue #58 · rmosolgo/graphql-ruby

暫時刪除所有的includes,改為使用https://github.com/salsify/goldiloader來進行處理。
試著使用goldiloader後,GraphQL運作良好,但也出現了一些系統無法運作的問題。

考虑到影响范围很广,我决定尝试使用 https://github.com/Shopify/graphql-batch(继续)

广告
将在 10 秒后关闭
bannerAds